how to create a list of classes where the class na

2019-09-20 11:36发布

Don't ask me why, but I need to do the following:
string cName = "ClassA";
List<cName> l = new List<cName>();
How can I do it?

my code:
public void MergeForm(List<object> lModel)
{
string className = lModel[0].GetType().Name;
List<className> list = new List<className>();
}
object - it is a class

4条回答
狗以群分
2楼-- · 2019-09-20 12:00

You cannot have List<cName> as static type, but you can create the instance:

IList l = (IList)Activator
    .CreateInstance(typeof(List<>)
    .MakeGenericType(Type.GetType(cName)));

cName needs to be the fully qualified name, though.

查看更多
聊天终结者
3楼-- · 2019-09-20 12:05

Use Assemmbly.GetTypes:

var l = Assembly.GetTypes().Where(t => t.Name == "ClassA").ToList();

If you have the full type name, you can use Assemmbly.GetType.

If you have the full type name and assembly-qualified name, and the type you seek is in another assembly, then use Type.GetType.

查看更多
不美不萌又怎样
4楼-- · 2019-09-20 12:17
Type ac;
string cName = "ClassA";
switch (cName)
{
case "ClassA":
ac = typeof(ClassA);
break;
case "ClassB":
ac = typeof(ClassB);
break;
default:
ac = typeof(System.String);    
break;
}
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(ac);
var l= Activator.CreateInstance(specificListType);
查看更多
对你真心纯属浪费
5楼-- · 2019-09-20 12:25

Take a look at the Activator.CreateInstance method.

查看更多
登录 后发表回答