【问题标题】:Specify generics where T should be interface指定 T 应该是接口的泛型
【发布时间】:2012-03-01 20:10:54
【问题描述】:

我在想一个通用方法,其中 T 应该是接口,但它可以是 IFace 的后代

public static T Get<T>(SomeClass foo) where T : IFace {
  if(smthing)
    return Activator.CreateInstance(type, true);
}

所以我可以打电话

Class.Get<IFace>(smth)
Class.Get<IFaceDescend>(smt)

但不是

Class.Get<Class2>(smt)

【问题讨论】:

标签: c# generics interface


【解决方案1】:

不,你不能这样做。您可以在执行时对其进行测试:

if (!typeof(T).IsInterface)
{
    throw ...;
}

...但您不能将其表达为T 的编译时约束。

【讨论】:

【解决方案2】:

这在当前的 C# 中是不可能的。

你唯一能做的就是在运行时验证事实,使用类似

if (!typeof(T).IsInterface) throw new ArgumentException("T must be an interface");

(请注意,我猜没有TypeArgumentException 可能是更好的选择。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多