具有泛型类型的 nameof
nameof with generic types
我正在尝试获取通用接口上方法的名称。我希望它能工作,因为类型部分是有效的 typeof:
//This does not compile
nameof(IGenericInterface<>.Method)
//This would compile
typeof(IGenericInterface<>)
我认为这应该是有效的 c#-6.0
还是我遗漏了什么或者有更好的方法来做到这一点。我不想使用字符串作为方法名称,因为如果方法被重命名代码会中断而不会出现任何构建时错误。
只需使用示例类型即可编译。
string name = nameof(IGenericInterface<int>.Method) // will be Method
这是意料之中的。根据 documentation,您的表达式是不允许的,因为它引用了未绑定的泛型类型:
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:
).
您可以通过提供通用参数来解决此限制:
nameof(IGenericInterface<object>.Method)
注意:我认为 Microsoft 应该调整 nameof
功能以允许引用未绑定泛型类型的方法。
我正在尝试获取通用接口上方法的名称。我希望它能工作,因为类型部分是有效的 typeof:
//This does not compile
nameof(IGenericInterface<>.Method)
//This would compile
typeof(IGenericInterface<>)
我认为这应该是有效的 c#-6.0
还是我遗漏了什么或者有更好的方法来做到这一点。我不想使用字符串作为方法名称,因为如果方法被重命名代码会中断而不会出现任何构建时错误。
只需使用示例类型即可编译。
string name = nameof(IGenericInterface<int>.Method) // will be Method
这是意料之中的。根据 documentation,您的表达式是不允许的,因为它引用了未绑定的泛型类型:
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
orvoid
), nullable types (Point?
), array types (Customer[,]
), pointer types (Buffer*
), qualified alias (A::B
), and unbound generic types (Dictionary<,>
), preprocessing symbols (DEBUG
), and labels (loop:
).
您可以通过提供通用参数来解决此限制:
nameof(IGenericInterface<object>.Method)
注意:我认为 Microsoft 应该调整 nameof
功能以允许引用未绑定泛型类型的方法。