解析是获取成员类型的唯一方法吗?

Hao*_*Hao 4 .net c# generics reflection

下面的反射代码返回:

System.Collections.Generic.IList`1[TestReflection.Car] Cars
Run Code Online (Sandbox Code Playgroud)

如何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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 12

最简单的方法是生成一个PropertyInfo代表有问题的属性,然后生成它的基础类型PropertyInfo.PropertyType.然后,只需检索此泛型类型的类型参数,您可以使用它Type.GetGenericArguments.

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