是解析,以获得会员类型的唯一途径? [英] Is parsing the only way to obtain the Member type?

查看:188
本文介绍了是解析,以获得会员类型的唯一途径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面返回的反射code:

  System.Collections.Generic.IList`1 [TestReflection.Car]汽车
 

我怎样才能获得汽车根通过反射型?不的IList<车> - 我怎样才能

 使用系统;
使用的System.Reflection;
使用System.Collections.Generic;

命名空间TestReflection
{
    类MainClass
    {
        公共静态无效的主要(字串[] args)
        {
            类型t = typeof运算(经销商);
            的MemberInfo [] MI = t.GetMember(汽车总动员);

            Console.WriteLine({0},英里[0]的ToString());
            到Console.ReadLine();
        }
    }

    一流的经销商
    {
        公众的IList<车>汽车{获得;组; }
    }

    类车
    {
        公共字符串CarModel {获得;组; }
    }
}
 

解决方案

最简单的方法是将产生的 的PropertyInfo 那些重新presented有问题的物业,然后通过的 PropertyInfo.PropertyType 。然后,它的检索类型参数此泛型类型,为此,你可以使用的 Type.GetGenericArguments

 键入carsElementType = typeof运算(经销商)
                        .GetProperty(汽车总动员)
                        .PropertyType // typeof运算(IList的<车>)
                        .GetGenericArguments()//新[] {typeof运算(车)}
                        。单(); // typeof运算(汽车)
 

The reflection code below returns:

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

How can I get the Cars root type through reflection? Not IList<Car> - how can I get 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; }
    }
}

解决方案

The easiest way would be to produce a PropertyInfo that represented the property in question and then its underlying type via PropertyInfo.PropertyType. Then it's just a matter of retrieving the type arguments for this generic type, for which you could use Type.GetGenericArguments.

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

这篇关于是解析,以获得会员类型的唯一途径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆