nameof with generic types

試著忘記壹切 提交于 2019-12-01 13:58:49

问题


I am trying to get the name of a method on a generic interface. I would expect this to work as the type part would be a valid typeof:

//This does not compile
nameof(IGenericInterface<>.Method)

//This would compile
typeof(IGenericInterface<>)

I think this should be valid C# 6 or am I missing something or is their a better way to do this. I don't want to use a string for the Method name as if method is renamed code would break without any build time errors.


回答1:


This is expected. According to the documentation, your expression is disallowed, because it refers to an unbound generic type:

Because the argument needs to be an expression syntactically, there are many things disallowed that are not useful to list. The following are worth mentioning that produce errors: predefined types (for example, int or void), nullable types (Point?), array types (Customer[,]), pointer types (Buffer*), qualified alias (A::B), and unbound generic types (Dictionary<,>), preprocessing symbols (DEBUG), and labels (loop:).

You can work around this limitation by supplying a generic parameter:

nameof(IGenericInterface<object>.Method)

Note: I think Microsoft should tweak nameof feature to allow references to methods of unbound generic types.




回答2:


Just use a sample type in order to compile.

string name = nameof(IGenericInterface<int>.Method) // will be Method


来源:https://stackoverflow.com/questions/33130234/nameof-with-generic-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!