创建变量类型列表
我想创建一个特定类型的列表。创建变量类型列表
我想用列表格式,但我所知道的是一个“System.Type的”
的类型有是可变的。我如何创建一个变量类型的列表?
我想要类似于此代码的东西。
public IList createListOfMyType(Type myType)
{
return new List<myType>();
}
你可以使用思考,这里是一个示例:
Type mytype = typeof (int);
Type listGenericType = typeof (List<>);
Type list = listGenericType.MakeGenericType(mytype);
ConstructorInfo ci = list.GetConstructor(new Type[] {});
List<int> listInt = (List<int>)ci.Invoke(new object[] {});
问题是我们不知道myType是typeof(int),所以你最后的语句不能是列表
可以使用泛型来完成:列表
这样的事情应该工作。
谢谢,这解决了我的问题。 – Jan 2010-03-23 07:20:06
在我开始工作之前,我不得不摆弄这一点。我是一个使用Type的新手,所以这里有一个代码片断,其他人可能会从你的Main或其他方法调用此createList方法时找到有用的代码片段: string [] words = {“stuff”,“things” ,“wordz”,“misc”}; var shtuff = createList(words.GetType()); – 2015-02-04 17:28:10
我意识到这是旧的,但@Jan,它解决了你的问题,它应该被标记为答案。 @kayleeFrye_onDeck你也可以'typeof(string [])' – 182764125216 2016-08-12 20:44:38
谢谢!这是一个很大的帮助。这里是我对实体框架的实现:
public System.Collections.IList TableData(string tableName, ref IList<string> errors)
{
System.Collections.IList results = null;
using (CRMEntities db = new CRMEntities())
{
Type T = db.GetType().GetProperties().Where(w => w.PropertyType.IsGenericType && w.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Entity.DbSet<>)).Select(s => s.PropertyType.GetGenericArguments()[0]).FirstOrDefault(f => f.Name == tableName);
try
{
results = Utils.CreateList(T);
if (T != null)
{
IQueryable qrySet = db.Set(T).AsQueryable();
foreach (var entry in qrySet)
{
results.Add(entry);
}
}
}
catch (Exception ex)
{
errors = Utils.ReadException(ex);
}
}
return results;
}
public static System.Collections.IList CreateList(Type myType)
{
Type genericListType = typeof(List<>).MakeGenericType(myType);
return (System.Collections.IList)Activator.CreateInstance(genericListType);
}
确保没有错误的设计,因为这是一个整体。 – Dykam 2010-03-22 15:32:10