[英]Can I set a property value with Reflection?
I know the name of a property in my C# class. 我知道我的C#类中的属性名称。 Is it possible to use reflection to set the value of this property?
是否可以使用反射来设置此属性的值?
For example, say I know the name of a property is string propertyName = "first_name";
例如,假设我知道属性的名称是
string propertyName = "first_name";
. 。 And there actaully exists a property called
first_name
. 并且存在一个名为
first_name
的属性。 Can I set it using this string? 我可以用这个字符串设置它吗?
Yes, you can use reflection - just fetch it with Type.GetProperty
(specifying binding flags if necessary), then call SetValue
appropriately. 是的,您可以使用反射 - 只需使用
Type.GetProperty
获取它(如果需要,指定绑定标志),然后适当地调用SetValue
。 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
}
}
If it's not a public property, you'll need to specify BindingFlags.NonPublic | BindingFlags.Instance
如果它不是公共属性,则需要指定
BindingFlags.NonPublic | BindingFlags.Instance
BindingFlags.NonPublic | BindingFlags.Instance
in the GetProperty
call. GetProperty
调用中的BindingFlags.NonPublic | BindingFlags.Instance
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.