gpt4 book ai didi

c# - 具有泛型类型的 nameof

转载 作者:行者123 更新时间:2023-11-30 18:17:30 26 4
gpt4 key购买 nike

我正在尝试获取通用接口(interface)上方法的名称。我希望它能工作,因为类型部分是一个有效的类型:

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

//This would compile
typeof(IGenericInterface<>)

我认为这应该是有效的 c#-6.0 或者我是否遗漏了什么或者是否有更好的方法来做到这一点。我不想使用字符串作为方法名称,因为如果方法被重命名代码会中断而不会出现任何构建时错误。

最佳答案

这是预料之中的。根据documentation ,您的表达式是不允许的,因为它指的是未绑定(bind)的泛型类型:

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)

注意:我认为微软应该调整 nameof允许引用未绑定(bind)泛型类型的方法的功能。

关于c# - 具有泛型类型的 nameof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43497562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com