C#反映具有可变数量类型参数的类型

时间:2011-11-05 08:09:09

标签: c# generics reflection

是否有可能在运行时获得具有可变数量类型参数的泛型类的类型?

即,基于数字,我们可以得到具有这么多元素的元组类型吗?

Type type = Type.GetType("System.Tuple<,>");

2 个答案:

答案 0 :(得分:6)

编写的方式是

Type generic = Type.GetType("System.Tuple`2");

泛型类型的格式很简单:

"Namespace.ClassName`NumberOfArguments"

`是角色96.(ALT + 96)。

但是我会避免使用字符串,它比使用typeof或更好的数组查找慢。 我会提供一个快速数千倍的静态函数...

private static readonly Type[] generictupletypes = new Type[]
{
    typeof(Tuple<>),
    typeof(Tuple<,>),
    typeof(Tuple<,,>),
    typeof(Tuple<,,,>),
    typeof(Tuple<,,,,>),
    typeof(Tuple<,,,,,>),
    typeof(Tuple<,,,,,,>),
    typeof(Tuple<,,,,,,,>)
};

public static Type GetGenericTupleType(int argumentsCount)
{
    return generictupletypes[argumentsCount];
}

答案 1 :(得分:0)

试试这个:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

public class MainClass 
{
    public static void Main()
    {
        PrintTypeParams(typeof(Tuple<int, double, string>));
    }

    private static void PrintTypeParams(Type t)
    {
        Console.WriteLine("Type FullName: " + t.FullName);
        Console.WriteLine("Number of arguments: " + t.GetGenericArguments().Length);
        Console.WriteLine("List of arguments:");
        foreach (Type ty in t.GetGenericArguments())
        {
            Console.WriteLine(ty.FullName);
            if (ty.IsGenericParameter)
            {
                Console.WriteLine("Generic parameters:");
                Type[] constraints = ty.GetGenericParameterConstraints();
                foreach (Type c in constraints)
                Console.WriteLine(c.FullName);
            }
        }
    }
}

输出:

 Type FullName: System.Tuple`3[[System.Int32, mscorlib, Version=4.0.0.0, Culture=
 neutral, PublicKeyToken=b77a5c561934e089],[System.Double, mscorlib, Version=4.0.
 0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib,
 Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
 Number of arguments: 3
 List of arguments:
 System.Int32
 System.Double
 System.String