【问题标题】:Do I have to create extension methods if I want to add type constrained (T=int) method onto a generic (T) class?如果我想将类型约束 (T=int) 方法添加到泛型 (T) 类中,是否必须创建扩展方法?
【发布时间】:2012-07-16 14:30:12
【问题描述】:

例如,我有一个 (non-static) 类 Foo<T>

我想为Foo 添加一个方法bar(),但是这个方法应该只适用于Foo<int>

因为我们不能重载类型约束,
我是否必须在单独的staticbar(this Foo<int> myFoo) 中创建扩展方法?

【问题讨论】:

    标签: c# generics extension-methods


    【解决方案1】:

    基本上,是的。 C#(以及一般的 CLR)不支持 C++ 中已知的模板特化。

    当你的类的实现根本不关心实际类型时使用类型参数。

    作为替代方案,添加运行时检查以确保仅在 typeof(T) == typeof(int) 上调用该方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多