问题描述
我有一个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)
推荐答案
//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 ^_^
这篇关于将列表转换为泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!