在C#中动态识别属性

Pau*_*els 1 c# properties

有没有办法在C#中动态识别设计时属性?例如:

class MyClass
{
    public string MyProperty1 { get; set; }  
}
Run Code Online (Sandbox Code Playgroud)

然后引用它像这样:

string myVar = "MyProperty1";
MyClass.myVar = "test";
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

如果要在运行时设置属性的值,并且只在运行时知道属性的名称,则需要使用Reflection.这是一个例子:

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);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)