开发者

How to get components of a Tuple in C#?

If I have a Tuple<int, double> declared, I would like to get the following.

  1. An object, I would imagine that this is a type object, that I can perform comparison on, to the effect of obj == typeof(Tuple<>) and it would return true.

  2. An array of Type objects, which is equivalent to new[]{typeof(int), typeof(double)}. This I can figu开发者_开发问答re out with reflection, since the tuple object exposes it's items as Properties, but then I don't know the order of these properties and the MSDN article says I can't rely on observation...

I need this in order to make a special case for a generic method, which should do something special if it's passed a tuple. Like so:

void foo<T>(...){
    if(T == Tuple<Q, S, ...>){
     //special code that needs to know what Q and S and ... are.
    }
}

Thanks in advance.


if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Tuple<,,>)) 
{
}

You must know the number of arguments for Tuple before-hand (in this case 3, so two commas). In other words, Tuple<> is distinct from Tuple<,>, etc. Once you know it's of the correct type, you may call:

typeof(T).GetGenericArguments()

Which returns an array of the type arguments passed to the Tuple.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜