我可以用Reflection设置属性值吗?

use*_*041 26 c# reflection

我知道我的C#类中的属性名称.是否可以使用反射来设置此属性的值?

例如,假设我知道属性的名称string propertyName = "first_name";.并且存在一个名为的财产first_name.我可以用这个字符串设置它吗?

Jon*_*eet 64

是的,您可以使用反射 - 只需获取它Type.GetProperty(必要时指定绑定标志),然后SetValue适当调用.样品:

using System;

class Person
{
    public string Name { get; set; }
}

class Test
{
    static void Main(string[] arg)
    {
        Person p = new Person();
        var property = typeof(Person).GetProperty("Name");
        property.SetValue(p, "Jon", null);
        Console.WriteLine(p.Name); // Jon
    }
}
Run Code Online (Sandbox Code Playgroud)

如果它不是公共财产,您需要BindingFlags.NonPublic | BindingFlags.InstanceGetProperty通话中指定.