有没有办法通过反射设置 C# 只读自动实现的属性?
标题说明了一切: 有没有办法通过反射设置 C# 只读自动实现的属性?
typeof(Change)
.GetProperty("ChangeType", BindingFlags.Instance | BindingFlags.Public)
.SetValue(myChange, change.ChangeType.Transform(),null);
此行给我一个错误:System.ArgumentException - {“未找到属性设置方法。”}。问题是我无法使用 GetField 因为没有字段。
在你问之前,我这样做是因为我需要“补充”一个已经完成的库,并且我无法访问它的代码。
The title says all:
Is there a way to set C# readonly auto-implemented Propeties through reflection?
typeof(Change)
.GetProperty("ChangeType", BindingFlags.Instance | BindingFlags.Public)
.SetValue(myChange, change.ChangeType.Transform(),null);
This line gives me an error : System.ArgumentException - {"Property set method not found."}. The thing is I can't use GetField because there are no fields.
Before you ask, I'm doing this because I need to "complement" an already finished library and I have no access to its code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可行,所以有些事情您没有告诉我们。您确定它是自动实现的属性吗?与您所看到的一致的解释是该属性不是自动实现的并且没有设置器。
也就是说,
会成功但
不会成功,并且会产生异常并显示您所看到的消息。
This should work, so there is something that you are not telling us. Are you sure that it's an auto-implemented property? An explanation consistent with what you are seeing is that the property is not auto-implemented and does not have a setter.
That is,
will succeed but
will not and it will produce the exception with the message that you are seeing.
显而易见的结论是
Change.ChangeType
没有公共实例设置器。the obvious conclusion would be that
Change.ChangeType
does not have public instance setter.