加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 名称与泛型类型

发布时间:2020-12-15 06:41:40 所属栏目:百科 来源:网络整理
导读:我试图在通用接口上获取一个方法的名称.我希望这可以工作,类型部分将是一个有效的类型: //This does not compilenameof(IGenericInterface.Method)//This would compiletypeof(IGenericInterface) 我认为这应该是有效的C#6或者我错过了一些东西,或者他们是
我试图在通用接口上获取一个方法的名称.我希望这可以工作,类型部分将是一个有效的类型:
//This does not compile
nameof(IGenericInterface<>.Method)

//This would compile
typeof(IGenericInterface<>)

我认为这应该是有效的C#6或者我错过了一些东西,或者他们是一个更好的方法来做到这一点.我不想使用方法名称的字符串,就好像方法被重命名的代码会中断而没有任何构建时间错误.

解决方法

这是预期的.根据 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)

注意:我认为微软应该调整name的功能,以允许引用未绑定的通用类型的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读