我可以使用 Reflection 设置属性值吗?
我知道我的 C# 类中的属性名称。是否可以使用反射来设置该属性的值?
例如,假设我知道属性的名称是 string propertyName = "first_name";
。实际上存在一个名为 first_name
的属性。我可以使用这个字符串来设置它吗?
I know the name of a property in my C# class. 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";
. And there actaully exists a property called first_name
. Can I set it using this string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以使用反射 - 只需使用
Type.GetProperty
(如有必要,指定绑定标志),然后调用
SetValue
适当地。示例:如果它不是公共属性,则需要指定 BindingFlags.NonPublic |
GetProperty
调用中的 BindingFlags.Instance。Yes, you can use reflection - just fetch it with
Type.GetProperty
(specifying binding flags if necessary), then callSetValue
appropriately. Sample:If it's not a public property, you'll need to specify
BindingFlags.NonPublic | BindingFlags.Instance
in theGetProperty
call.