我可以设置反射属性值? [英] 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?
举例来说,说我知道属性的名称是字符串参数propertyName =FIRST_NAME;
。还有actaully存在一个名为属性 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可| BindingFlags.Instance
在的getProperty
电话。
If it's not a public property, you'll need to specify BindingFlags.NonPublic | BindingFlags.Instance
in the GetProperty
call.
这篇关于我可以设置反射属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!