我正在尝试更改变量值,但我只有变量名作为字符串。我知道这通常并不理想,但请假设这对我的情况是必要的。我要更改的变量是 type Element
,我创建的一个类如下所示:
public class Element
{
public string TopBoundReplace;
public string RightBoundReplace;
public string BottomBoundReplace;
public List<string> ConfidenceString {get; set;}
public string LeftBoundReplace { get; set; }
public string Regex { get; set; }
public string ReplaceString { get; set; }
public List<int> LeftBound { get; set; }
public List<int> TopBound { get; set; }
public List<int> BottomBound { get; set; }
public List<int> RightBound { get; set; }
public string Whitelist { get; set; }
public List<System.Drawing.Rectangle> Rectangle { get; set; }
public System.Drawing.Rectangle SourceBox { get; set; }
public List<string> Value { get; set; }
public Element()
: this("", "", "", new List<int>(), new List<int>(), new List<int>(),new List<int>(), "", new List<Rectangle>(), new System.Drawing.Rectangle(), new List<string>(), new List<string>())
{
}
public Element(string leftBoundReplace, string regex, string replaceString, List<int> leftBound, List<int> topBound, List<int> bottomBound, List<int> rightBound, string whitelist, List<System.Drawing.Rectangle> rectangle, System.Drawing.Rectangle sourceBox, List<string> value, List<string> confidenceString)
{
Regex = regex;
ReplaceString = replaceString;
LeftBound = leftBound;
TopBound = topBound;
BottomBound = bottomBound;
RightBound = rightBound;
Whitelist = whitelist;
Rectangle = rectangle;
SourceBox = sourceBox;
Value = value;
LeftBoundReplace = leftBoundReplace;
ConfidenceString = confidenceString;
}
}
元素在另一个名为 ocrVar 的类中初始化,如下所示(为本问题的目的而修剪):
public class ocrVar
{
public static Element DueDate = new Element();
public static Element AmountDue = new Element();
public static Element BillDate = new Element();
}
因此,通常,我会通过执行以下操作来编辑有问题的值:
ocrVar.DueDate.Value[0] = "10/25/2012";
如何仅使用字符串值作为变量名来执行此操作?我尝试了一些反射的东西:
Type myType = ocrVar.BillDate.GetType();
PropertyInfo myPropInfo = myType.GetProperty("DueDate");
myType 最终获得了正确的类型 ( Element
),但 myPropInfo 在运行上述代码时仍然为空,因为“DueDate”不是类的属性Element
,而是类的属性ocrVar
。我想做类似上面的代码来获取Element
DueDate 中的值,这样我就可以操纵这些值,然后将它们放回 ocrVar.DueDate。