2011-11-05 108 views

回答

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

哈,我看到这是他们是如何在伊利诺斯州命名,当我的反思很疯狂时,我很愚蠢,错过了这个机会!谢谢! – Darkzaelus

+1

:)不,你不是愚蠢的,是违反直觉的,我同意你的看法。 –

+1

关于优化,你可能是对的。我目前正在编写一个可以处理多个泛型类的编译器,但为常见类型提供查找表可能非常有用 – Darkzaelus

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