下面的反射代码返回:
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; }
}
}
最简单的方法是生成一个PropertyInfo http://msdn.microsoft.com/en-us/library/8z852kf5.aspx代表有问题的财产,然后是其基础类型PropertyInfo.PropertyType http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.propertytype.aspx。然后只需检索该泛型类型的类型参数即可,您可以使用Type.GetGenericArguments http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx.
Type carsElementType = typeof(Dealer)
.GetProperty("Cars")
.PropertyType // typeof(IList<Car>)
.GetGenericArguments() // new[] { typeof(Car) }
.Single(); // typeof(Car)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)