Dynamically identifying properties in C#
Is there a way to dynamically identify design time properties in C#? For example:
class MyClass
{
public string MyProperty1 { get; set; }
}
And then reference it something like this:
string myVar = "MyProperty1";
MyCla开发者_C百科ss.myVar = "test";
If you want to set the value of a property at runtime and the name of the property is only known at runtime you need to use Reflection. Here's an example:
public class MyClass
{
public string MyProperty1 { get; set; }
}
class Program
{
static void Main()
{
// You need an instance of a class
// before being able to set property values
var myClass = new MyClass();
string propertyName = "MyProperty1";
// obtain the corresponding property info given a property name
var propertyInfo = myClass.GetType().GetProperty(propertyName);
// Before trying to set the value ensure that a property with the
// given name exists by checking for null
if (propertyInfo != null)
{
propertyInfo.SetValue(myClass, "test", null);
// At this point you've set the value of the MyProperty1 to test
// on the myClass instance
Console.WriteLine(myClass.MyProperty1);
}
}
}
how about simply implementing an indexer on your class
public class MyClass
{
public string MyProperty1 { get; set; }
public object this[string propName]
{
get
{
return GetType().GetProperty(propName).GetValue(this, null);
}
set
{
GetType().GetProperty(propName).SetValue(this, value, null);
}
}
}
and then you can do something very similar
var myClass = new MyClass();
string myVar = "MyProperty1";
myClass[myVar] = "test";
Yes, of course you can. You need to get a FieldInfo
object relating to the property that you want to set.
var field = typeof(MyClass).GetField("MyProperty1");
then from that field info object, you can set the value of any instance of that class.
field.SetValue(myinstanceofmyclass, "test");
See MSDN: FieldInfo for other fun stuff you can do with reflection.
精彩评论