使用 PropertyInfo.GetValue 获取没有 getter 的 AutoProperty 的值
我试图在单元测试中获取字符串属性的值。问题是该属性没有 getter。该属性也被声明为 AutoProperty 并且没有支持字段。
我试图在 System.Reflection 命名空间中使用 PropertyInfo.GetValue(...) 。但是我得到 System.ArgumentException :未找到属性 Get 方法。
我不拥有该类型的代码,因此无法向该属性添加吸气剂。
如何获得这样一处房产的价值?
I am trying to get the value of a string property in a unit test. The problem is that the property has no getter. The property is also declared as an AutoProperty and has no backing field.
I am trying to use PropertyInfo.GetValue(...) in the System.Reflection namespace. However I get System.ArgumentException : Property Get method was not found.
I do not own the code of that type so I am unable to add a getter to the property.
How does one get the value of such a property?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要找到编译器使用反射自动生成的支持字段。然后,使用其
FieldInfo
您将能够读取其值。我不确定这是否可能。好的,我有解决方案:
通过以下类
和以下扩展方法,
您可以使用以下代码实现您想要的:
You would somehow need to find the backing field that was auto-generated by compiler using Reflection. And then, using its
FieldInfo
you will be able to read its value. And I am not sure if it is possible at all.OK, I have the solution:
With following class,
and following extension method,
You can achieve what you want by using following code:
该属性将有一个支持字段,只是我们不知道它的名称(并且它的名称不会是有效的标识符)。如果这是一项一次性任务,那么您最好使用 .NET 反射器 并找到由设置器设置的字段。
我不认为你可以通过 Reflection 做任何事情(除非你想解析 setter 的 IL 方法体来找到它设置的字段
The property will have a backing field, it's just that we don't know it's name (and it's name will not be a valid identifier). If this is for a one-off task, then you might do well to crack it open using .NET reflector and find the field that's being set by the setter.
I don't think there's anything you can do via Reflection (unless you want to parse the IL method body of the setter to find which field it's setting