Is it possible to specify a constraint to a C# generic parameter, where that parameter must be abstract? 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
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. 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.