是否可以为C#通用参数指定约束,而该参数必须是抽象的?
因此,我目前有一种方法,其中泛型参数必须具有无参数构造函数,但现在遇到了需要抽象T的情况,因此我希望使用仅接受抽象T的方法重载该方法。
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
}
如果我怀疑答案是“您不能这样做”,是否有任何明智的解决方法?
最佳答案
您不能指示编译器检查type参数是否为抽象。但是您可以进行运行时检查。
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
}
要么:
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);
}
}