简体   繁体   English

从属性而不是名称获取PropertyInfo

[英]Get PropertyInfo from property instead of name

Say, for example, I've got this simple class: 比方说,我有这个简单的类:

public class MyClass
{
  public String MyProperty { get; set; }
}

The way to get the PropertyInfo for MyProperty would be: 获取MyProperty的PropertyInfo的方法是:

typeof(MyClass).GetProperty("MyProperty");

This sucks! 这糟透了!

Why? 为什么? Easy: it will break as soon as I change the Name of the Property, it needs a lot of dedicated tests to find every location where a property is used like this, refactoring and usage trees are unable to find these kinds of access. 容易:一旦我更改属性的名称就会中断,它需要很多专门的测试才能找到像这样使用属性的每个位置,重构和使用树都无法找到这些类型的访问权限。

Ain't there any way to properly access a property? 有没有办法正确访问一个属性? Something, that is validated on compile time? 什么,在编译时验证?
I'd love a command like this: 我喜欢这样的命令:

propertyof(MyClass.MyProperty);

The closest you can come at the moment is to use an expression tree: 你现在最接近的是使用表达式树:

GetProperty<MyClass>(x => x.MyProperty)

and then suck the PropertyInfo out in GetProperty (which you'd have to write). 然后在GetProperty (你必须写)中吸取PropertyInfo However, that's somewhat brittle - there's no compile-time guarantee that the expression tree is only a property access. 但是,这有点脆弱 - 没有编译时保证表达式树只是属性访问。

Another alternative is to keep the property names that you're using somewhere that can be unit tested easily, and rely on that. 另一种方法是保持您正在使用的属性名称可以轻松进行单元测试,并依赖于此。

Basically what you want is the mythical infoof operator which has been talked about many times by the C# team - but which hasn't made the cut thus far :( 基本上你想要的是C#团队多次讨论的神话infoof运算符 - 但到目前为止还没有进行过切割:(

In the time since this question was posted, C# 6 has been released with the nameof operator . 自发布此问题以来,C#6已经与nameof运营商一起发布。 This allows a property to be accessed with the following 这允许使用以下内容访问属性

PropertyInfo myPropertyInfo = typeof(MyClass).GetProperty(nameof(MyClass.MyProperty));

If you rename the property, this code will not compile (actually it will, since the rename will change this line of code as well if the rename is done properly). 如果重命名该属性,则此代码将无法编译(实际上它将会,因为如果重命名正确完成,重命名将更改此行代码)。

The whole point of reflection is to be able to access stuff at runtime. 反思的全部意义是能够在运行时访问内容。 If we assume your operator would work, you already have the class information and thus the property, making the whole thing completely useless. 如果我们假设您的操作员可以工作,那么您已经拥有了类信息,因此也拥有了属性,使整个事情完全无用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM