【发布时间】:2018-05-19 14:14:57
【问题描述】:
我有一堆由 EF 生成的类,它们是简单的表并且具有相似的结构:
public class Contact
{
public int ID { get; set; }
public string Description { get; set; }
}
public class Member
{
public int ID { get; set; }
public string Description { get; set; }
}
我还有一个返回指定类型对象的方法:
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
我想做的是这样的:
public ActionResult GetAll(string ClassType) // ClassType will be the name of one of the classes above
{
Object LookupType = GetInstance<Object>(ClassType);
List<LookupType> AllList = new List<LookupType>();
AllList = repo.GetAll<LookupType>().ToList<LookupType>(); // some generic method that will return a list;
}
这让编译器发疯,因为我使用变量 (LookupType) 而不是真正的类型来构建列表。但是,这些都不起作用:
List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
两者都会导致错误 - “使用泛型类型 List 需要 1 个类型参数”。
有没有合适的方法来做到这一点?有没有办法直接将 ClassType 转换为类型,而无需先使其成为对象(我希望从中派生类型)?
【问题讨论】: