是否可以为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
}如果像我怀疑的那样,答案是“你不能这样做”,那么有没有什么明智的变通办法呢?
发布于 2016-03-22 18:23:40
不能指示编译器检查类型参数是否为抽象参数。但是你可以做一个运行时检查。
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);
}
}https://stackoverflow.com/questions/36151409
复制相似问题