将列表转换为泛型类型? [英] Cast list to generic type?

查看:115
本文介绍了将列表转换为泛型类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个T GetConfig< t>方法。这可以返回一个基类型或一个List< int>



我现在有一个案例,其中T是List< int>,我的结果是List< int> ;,但是我无法将List< int>转换为Type T。



有一个简单的方法吗?

或者我必须创建列表< t> GetConfigList< t>方法?



Ta

Andy



我有什么尝试过:



这不起作用:

Hi,

I have a "T GetConfig<t>" method. This could return a base type or a List<int>

I now have a case where T is List<int>, my result is List<int>, but I "cannot cast List<int> to Type T".

Is there an easy way around this?
Or do I have to create a "List<t> GetConfigList<t>" method?

Ta
Andy

What I have tried:

Well this didn't work:

(T)SelectMenu.SelectByIdAndSelected(menuId.Value, (int)config.Value)

推荐答案

我为此感到非常自豪:



我没有完全解释它,但方法确实需要做不同的事情来获得基本类型或列表类型设置。我可以将它分流到Configuration类,但我还是已经开始创建第二个List方法。



分离< list< T>>来自< T>方法无论如何都是一件好事,所以每种方法都不会太复杂。



I'm very proud of myself for this:

I didn't explain it fully, but the methods do need to do different things to get the base type or list type setting. I could have shunted this down to the Configuration class, but I had already started creating a second List method anyway.

Separating the <list<T>> from the <T> method is prolly a good thing anyway so each method doesn't get too complex

//This is an object in my MembershipUserClass
public T GetCompanySetting<t>(string key)
{
    //Check if the generic type
    if (typeof (T).IsGenericType && typeof (T).GetInterfaces().Contains(typeof (System.Collections.IEnumerable)))
    {
        //Assume the enumerable is generic.  The caller should know this
        var t = typeof (T).GetGenericArguments()[0];

        //Only way to use t is with reflection (this was the knowledge I was missing)
        MethodInfo method = typeof (Configuration).GetMethod("QueryList").MakeGenericMethod(new[] {t});

        //Convert works fine here 
        return (T)method.Invoke(null,new object []{ CompanyId, null, "AccountManagement", key, null});
    }
    //Normal call with T not enumerable.  This method does check for nullable types so it will return the correct default if the setting does not exist.  Again, the caller should know this
    return Configuration.Query<t>(CompanyId, null, "AccountManagement", key);
}

</t></t>





我希望此方法对于来电者来说是on rails。我的同事将使用这种方法在VB中写,并且对泛型不太熟悉。



谢谢你看看,伙计们^ _ ^



I wanted this method to be "on rails" for the caller. My colleague who will use this method writes in VB and isn't too familiar with generics.

Thanks for taking a look, guys ^_^


这篇关于将列表转换为泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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