我有一个 Account
类的实例。每个帐户对象都有一个所有者、引用等。
我可以访问帐户属性的一种方法是通过像
这样的访问器account.Reference;
但我希望能够使用动态字符串选择器访问它,例如:
account["PropertyName"];
就像在 JavaScript 中一样。所以我会有 account["Reference"]
返回值,但我也希望能够在之后分配一个新值,例如:
account["Reference"] = "124ds4EE2s";
我注意到我可以使用
DataBinder.Eval(account,"Reference")
获取基于字符串的属性,但使用它我无法为属性赋值。
知道我该怎么做吗?
最佳答案
首先,你应该避免使用这个; C# 是一种强类型语言,因此请充分利用伴随该方面的类型安全和性能优势。
如果您有正当理由动态获取和设置属性的值(换句话说,当无法在代码中定义类型和/或属性名称时),那么您将不得不使用反射(reflection)。
最内联的方式是这样的:
object value = typeof(YourType).GetProperty("PropertyName").GetValue(yourInstance);
...
typeof(YourType).GetProperty("PropertyName").SetValue(yourInstance, "value");
但是,您可以缓存 PropertyInfo
对象以使其更具可读性:
System.Reflection.PropertyInfo prop = typeof(YourType).GetProperty("PropertyName");
object value = prop.GetValue(yourInstance);
...
prop.SetValue(yourInstance, "value");
关于c# - 以字符串形式访问对象属性并设置其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2905187/