具有泛型类型的名称 [英] nameof with generic types

查看:99
本文介绍了具有泛型类型的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在通用接口上获取方法的名称。我预计这会起作用,因为类型部分将是一个有效的typeof:

  //这不会编译
nameof(IGenericInterface<>方法)

//这将编译
typeof(IGenericInterface<>)

我认为这应该是有效的C#6,或者我错过了一些东西或者是他们更好的方式来做到这一点。我不想为方法名称使用字符串,就好像方法被重命名一样,代码将会中断而不会产生任何编译时错误。 这是预料之中的。根据文档,您的表达式是不允许的,因为它引用了一个未绑定的泛型类型:


因为参数需要在语法上是一个表达式,所以有许多东西是不允许的,对列表没有用处。以下是值得一提的产生错误:预定义类型(例如, int void ),可为空的类型( Point ),数组类型( Customer [,] ),指针类型( Buffer * ),合格的别名( A :: B )和未绑定的泛型类型( Dictionary<,> ),预处理符号( DEBUG )和标签( loop:)。


您可以通过提供泛型参数来解决此限制:

  nameof(IGenericInterface< object> .Method)

注意:我认为微软应该调整 nameof 特性来允许引用未绑定泛型类型的方法。


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.

解决方案

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.

这篇关于具有泛型类型的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆