简体   繁体   English

C#nameof运算符引用实例属性可以没有实例吗?

[英]Can C# nameof operator reference instance property without instance?

I regularly want to get the name of an instance property of a type, when I have no instance. 当我没有实例时,我经常想要获取类型的实例属性的名称。 Currently to do this, I use the following inhouse function which interprets the Expression[Func[T, object]] parameter and returns the property name: 目前要执行此操作,我使用以下内部函数来解释Expression[Func[T, object]]参数并返回属性名称:

var str = LinqExtensions.NameOf<ClientService>(x => x.EndDate);
// Now str == "EndDate"

However it seems a shame not to use the built in nameof operator. 但是,不使用内置的nameof运算符似乎是一种耻辱。

Unfortunately it seems that the nameof operator requires either an instance, or, to reference a static properties. 不幸的是, nameof运算符似乎需要一个实例,或者引用一个静态属性。

Is there a neat way to use the nameof operator instead of our in house function? 有没有一种巧妙的方法来使用nameof运算符而不是我们的内部函数? For example: 例如:

nameof(ClientService.EndDate) // ClientService.EndDate not normally syntactically valid as EndDate is instance member

EDIT 编辑

I was completely wrong, the syntax nameof(ClientService.EndDate) as described actually works as is. 我完全错了,所描述的语法nameof(ClientService.EndDate)实际上是按原样工作的。

From the documentation : 文档

In the examples you see that you can use a type name and access an instance method name. 在示例中,您会看到可以使用类型名称并访问实例方法名称。 You do not need to have an instance of the type[emphasis mine] 您不需要具有该类型的实例 ... [强调我的]

Ie you should be able to write nameof(ClientService.EndDate) and have it work, contrary to your statement in the question that this would be "not normally syntactically valid" . 即你应该能够写出nameof(ClientService.EndDate)并让它工作,这与你在问题中的声明相反,即“通常语法无效”

If you are having trouble with the syntax, please provide a good Minimal, Complete, and Verifiable code example that reliably reproduces whatever error you're getting, and provide the exact text of the error message. 如果您遇到语法问题,请提供一个良好的Minimal,Complete和Verifiable代码示例 ,可以可靠地重现您获得的任何错误,并提供错误消息的确切文本。

Great answer by @Peter Duniho. @Peter Duniho的精彩回答。

In case of name clashes, you can also do the following: 如果出现名称冲突,您还可以执行以下操作:

ClientService clientservice;
var str = nameof(clientservice.EndDate);

Not efficient, but curious enough. 效率不高,但很好奇。

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

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