2010-12-15 79 views
4

反射代码如下收益:是解析获取成员类型的唯一方法吗?

System.Collections.Generic.IList`1[TestReflection.Car] Cars 

我怎样才能获得通过反射Cars根型?不是IList<Car> - 我怎样才能得到Car

using System; 
using System.Reflection; 
using System.Collections.Generic; 

namespace TestReflection 
{ 
    class MainClass 
    { 
     public static void Main(string[] args) 
     { 
      Type t = typeof(Dealer); 
      MemberInfo[] mi = t.GetMember("Cars"); 

      Console.WriteLine("{0}", mi[0].ToString()); 
      Console.ReadLine(); 
     } 
    } 

    class Dealer 
    { 
     public IList<Car> Cars { get; set; } 
    } 

    class Car 
    { 
     public string CarModel { get; set; } 
    } 
} 

回答

12

的最简单的方法是将产生PropertyInfo其表示通过PropertyInfo.PropertyType有问题的属性,然后它的基础类型。然后,它只是检索此泛型的类型参数,您可以使用它Type.GetGenericArguments

Type carsElementType = typeof(Dealer) 
         .GetProperty("Cars") 
         .PropertyType // typeof(IList<Car>) 
         .GetGenericArguments() // new[] { typeof(Car) } 
         .Single(); // typeof(Car) 
1

您将Type对象放在一个封闭的Type中,然后使用GetGenericArguments返回所有类型的列表替换为通用参数。

var l = new List<int>(); 
foreach(var genericArg in l.GetType().GetGenericArguments()) 
    Console.WriteLine(genericArg); // returns Int32 
相关问题