简体   繁体   English

约束泛型参数是抽象的

[英]Constraining generic parameter to be abstract

Is it possible to specify a constraint to a C# generic parameter, where that parameter must be abstract? 是否可以为C#泛型参数指定约束,其中该参数必须是抽象的? So I currently have a method where the generic parameter must have a parameterless constructor but I've now run in to a scenario where I need an abstract T so I was hoping to overload the method with one that accepts only abstract Ts 所以我目前有一个方法,其中泛型参数必须有一个无参数构造函数,但我现在运行到我需要一个抽象T的场景,所以我希望用一个只接受抽象Ts的方法重载该方法

public static void SomeMethod<T>(IEnumberable<T> SomeParam) where T:SomeBase, new()
{
  T tThing = new T();
  //do something simple
}
public static T SomeOtherMethod<T>(IEnumberable<T> SomeParam) where T:SomeBase, new()
{
  T tThing = new T();
  //do something simple
}

public static void SomeMethod<T>(IEnumberable<T> SomeParam) where T:SomeBase, abstract()
{
 //do something clever
}
public static T SomeOtherMethod<T>(IEnumberable<T> SomeParam) where T:SomeBase, abstract()
{
 //do something clever
}

If, as I suspect, the answer is "you can't do this", are there any sensible workarounds? 如果我怀疑答案是“你不能这样做”,那么是否有任何合理的解决方法?

You cannot instruct the compiler to check that the type parameter is abstract. 您无法指示编译器检查type参数是否为抽象。 But you can do a runtime check. 但是你可以做一个运行时检查。

public static void SomeMethod<T>(IEnumerable<T> SomeParam) where T:SomeBase
{
    Type type = typeof(T);
    if(type.IsAbstract)
    {
        throw new Exception(string.Format("Cannot use SomeMethod with type {0} because it is abstract.", type.FullName)); 
    }

    // Do the actual work
}

Or: 要么:

public static void SomeMethod<T>(IEnumerable<T> SomeParam) where T:SomeBase
{
    Type type = typeof(T);
    if(type.IsAbstract)
    {
        SomeMethodAbstract<T>(SomeParam);
    }
    else
    {
        SomeMethodNonAbstract<T>(SomeParam);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM