我可以使用反射设置属性值吗? [英] Can I set a property value with Reflection?
问题描述
我知道我的 C# 类中的属性名称.是否可以使用反射来设置该属性的值?
I know the name of a property in my C# class. Is it possible to use reflection to set the value of this property?
例如,假设我知道一个属性的名称是 string propertyName = "first_name";
.并且实际上存在一个名为 first_name
的属性.我可以用这个字符串设置吗?
For example, say I know the name of a property is string propertyName = "first_name";
. And there actaully exists a property called first_name
. Can I set it using this string?
推荐答案
是的,您可以使用反射 - 只需使用 Type.GetProperty
(必要时指定绑定标志),然后调用 SetValue
适当.示例:
Yes, you can use reflection - just fetch it with Type.GetProperty
(specifying binding flags if necessary), then call SetValue
appropriately. Sample:
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
}
}
如果它不是公共属性,则需要指定 BindingFlags.NonPublic |
.GetProperty
调用中的 BindingFlags.Instance
If it's not a public property, you'll need to specify BindingFlags.NonPublic | BindingFlags.Instance
in the GetProperty
call.
这篇关于我可以使用反射设置属性值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!