gpt4 book ai didi

c# - 在不指定类型参数的情况下对泛型类的成员使用 nameof

转载 作者:太空狗 更新时间:2023-10-29 21:49:21 24 4
gpt4 key购买 nike

class Foo<T>
{
public T Bar() { /* ... */ }
}

我想将 Bar 的名字传递给 Type.GetMethod(string) .我可以这样做 someType.GetMethod(nameof(Foo<int>.Bar)) ,但是int在这里完全是任意的;有什么办法可以省略吗?可悲的是,nameof(Foo<>.Bar)不起作用。

在这个玩具箱中没什么大不了的,但如果有多个类型参数,尤其是如果它们有 where附加到它们的约束条件,将它们全部拼写出来可能成为一项任务。

最佳答案

nameof 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:).

您可能做的最好的事情就是指定 Bar在界面中,并使用 nameof(IFoo.Bar) .当然,如果Bar,那不是一个选项。包括与 T 相关的内容在其签名中(就像在这种特定情况下一样)。


另一种选择是创建一个接口(interface),其中每个 T替换为 object .然后具体类型显式实现接口(interface),同时实现相同方法的泛型版本。

这有一些缺点:

  • 更大的 API 表面
  • 更困难且更容易出错的重构
  • 失去编译时类型安全,因为调用者可能使用 object界面。

仅仅使用 nameof 可能是不合理的,但在某些情况下,由于其他原因,这种策略是有意义的。在这些情况下,能够使用 nameof只是一个方便的奖励。

关于c# - 在不指定类型参数的情况下对泛型类的成员使用 nameof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33815111/

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