how to pass multiple generic arguments
i was wondering if there's a way to build a class which can accept multiple generic arguments that aren't known at compile time
class Something<T,V,U>
this example shows a class which would expect to receive 3 generic arguments at run time. i'm looking for a way to spec开发者_开发技巧ify a class which would except multiple arguments of a varied amount
something along the line of
class Something<T[]>
which i could later expose using reflection
Type [] types = GetType().GetGenericArguments();
You can't specify an unknown number of generics. The closest you can get is to define all possible variations, or at least as many as you're willing to handle. I recommend using an abstract base class too. For example:
public abstract class Something { }
public class Something<T1> : Something { }
public class Something<T1, T2> : Something { }
public class Something<T1, T2, T3> : Something { }
public class Something<T1, T2, T3, T4> : Something { }
public class Something<T1, T2, T3, T4, T5> : Something { }
...
The abstract class is useful for when you need to reference the type but don't know the number of generic arguments.
Depending on your evil intentions you may end up writing a lot of redundant code using this solution in which case you should reconsider your use of generics.
You can make some class - a kind of
public static class TypeHelper
{
public static IEnumerable<Type> GetTypeCombination(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(T<,>))
return type.GetGenericArguments().SelectMany(GetTypeCombination);
return new Type[] { type };
}
}
public class T<T1, T2>
{
public static IEnumerable<Type> GetTypeCombination()
{
return typeof(T1).GetTypeCombination()
.Concat(typeof(T2).GetTypeCombination());
}
}
and to use that as
var list = T<int, T<string, int[]>>.GetTypeCombination().ToList();
to get (pass) dynamic list of types - not sure it's the best way
精彩评论