如何在泛型方法中获取具体类型 [英] How to get concrete type in generic method

查看:48
本文介绍了如何在泛型方法中获取具体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回实现接口的对象列表的方法:

I have a method that returns a List of objects that implement an interface:

private List<IFoo> GetData(string key)
{    
   ...returns a different concrete implementation depending on the key
    switch (key)
    {
        case "Bar":
            return new List<Bar>();//Bar:IFoo
            break;

        case "Foo":
            return new List<Foo>();//Foo:IFoo
            break;


        case "FooBar":
            return new List<FooBar>();//FooBar:IFoo
            break;
        //etc etc - (quite a lot of these)
    }
}

我想将结果转换为数据表:

And I want to convert the result to a DataTable:

var result = GetData("foobar");
return ConvertToDataTable(result)

我的 ConvertToDataTable 实现看起来像这样:

and my implementation of ConvertToDataTable looks something like this:

private DataTable ConvertToDataTable<T>(IEnumerable<T> data)
{
    //problem is typeof(T) is always IFoo - not FooBar
    PropertyInfo[] properties = typeof(T).GetProperties();

    DataTable table = new DataTable();
    foreach (var prop in properties)
    {
        table.Columns.Add(prop.DisplayName, prop.PropertyType);
    }
    //etc..
}

如何在通用 ConvertToDataTable 方法中获取基础类型?

How can I get the underlying type in the generic ConvertToDataTable method?

推荐答案

用在运行时计算的 .GetType 替换在编译时计算的 typeof ,您将获得 coorect 类型,而不是接口:

Replace typeof which is evaluated at compileTime by .GetType which is evaluated at runtime and you will get the coorect type, not the interface:

private DataTable ConvertToDataTable<T>(IEnumerable<T> data)
    {
        Type dataType;
        if (data != null && data.Count() != 0)
        {
            //problem is typeof(T) is always IFoo - not FooBar
            //typeof(T) will always return IFoo

            //Will return the correct type
            dataType = data.First().GetType();
        }
        else
        {
            return new DataTable();
            //or throw ?
        }

        PropertyInfo[] properties = dataType.GetProperties();

        DataTable table = new DataTable();
        foreach (var prop in properties)
        {
            table.Columns.Add(prop.DisplayName, prop.PropertyType);
        }
        //etc..
    }

这篇关于如何在泛型方法中获取具体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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