[英]Constraining generic parameter to be abstract
是否可以为C#泛型参数指定约束,其中该参数必须是抽象的? 所以我目前有一个方法,其中泛型参数必须有一个无参数构造函数,但我现在运行到我需要一个抽象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
}
如果我怀疑答案是“你不能这样做”,那么是否有任何合理的解决方法?
您无法指示编译器检查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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.