以字符串形式访问对象属性并设置其值 [英] Accessing object property as string and setting its value
问题描述
我有一个Account
类的实例.每个帐户对象都有一个所有者,引用等.
I have an instance of the Account
class. Each account object has an owner, reference, etc.
访问帐户属性的一种方法是通过
One way I can access an accounts properties is through accessors like
account.Reference;
但是我希望能够使用动态字符串选择器来访问它,例如:
but I would like to be able to access it using dynamic string selectors like:
account["PropertyName"];
就像在JavaScript中一样.因此,我将拥有account["Reference"]
,它将返回该值,但我还希望能够在此之后分配一个新值,例如:
just like in JavaScript. So I would have account["Reference"]
which would return the value, but I also would like to be able to assign a new value after that like:
account["Reference"] = "124ds4EE2s";
我注意到我可以使用
DataBinder.Eval(account,"Reference")
要获取基于字符串的属性,但是使用该属性我无法为该属性分配值.
to get a property based on a string, but using this I can't assign a value to the property.
关于我该怎么做的任何想法?
Any idea on how I could do that?
推荐答案
首先,您应避免使用此方法. C#是一种强类型语言,因此请充分利用该方面带来的类型安全性和性能优势.
First of all, you should avoid using this; C# is a strongly-typed language, so take advantage of the type safety and performance advantages that accompany that aspect.
如果您有合理的理由动态获取和设置属性的值(换句话说,当代码中无法定义类型和/或属性名称时),则必须使用反思.
If you have a legitimate reason to get and set the value of a property dynamically (in other words, when the type and/or property name is not able to be defined in the code), then you'll have to use reflection.
最内联的方式是这样的:
The most inline-looking way would be this:
object value = typeof(YourType).GetProperty("PropertyName").GetValue(yourInstance);
...
typeof(YourType).GetProperty("PropertyName").SetValue(yourInstance, "value");
但是,您可以缓存PropertyInfo
对象以使其更具可读性:
However, you can cache the PropertyInfo
object to make it more readable:
System.Reflection.PropertyInfo prop = typeof(YourType).GetProperty("PropertyName");
object value = prop.GetValue(yourInstance);
...
prop.SetValue(yourInstance, "value");
这篇关于以字符串形式访问对象属性并设置其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!