积极答复者
string 转 class

问题
答案
-
直接写List<Dog>不就可以了吗?比如:
List<Dog> list = new List<Dog>()
还是说你想根据一个字符串来构造一个List<>?
这样的话可以参考以下代码:
namespace Test { public class Program { public static IList GetList(string className) { Type classType = Type.GetType(className); Type listType = typeof(List<>).MakeGenericType(classType); return Activator.CreateInstance(listType) as IList; } public static void Main() { IList dogList = GetList("Test.Dog");//一定要在类型名前面加上命名空间 dogList.Add(new Dog()); try { dogList.Add(new Cat());//出错,因为dogList是List<Dog>类型,不能添加Cat } catch (Exception ex) { Console.WriteLine(ex); } IList catList = GetList("Test.Cat");//一定要在类型名前面加上命名空间 catList.Add(new Cat()); try { catList.Add(new Dog());//出错,因为catList是List<Cat>类型,不能添加Dog } catch (Exception ex) { Console.WriteLine(ex); } } } public class Dog { } public class Cat { } }
- 已建议为答案 ThankfulHeartModerator 2014年5月2日 6:27
- 已标记为答案 Barry WangModerator 2014年5月2日 8:54
全部回复
-
直接写List<Dog>不就可以了吗?比如:
List<Dog> list = new List<Dog>()
还是说你想根据一个字符串来构造一个List<>?
这样的话可以参考以下代码:
namespace Test { public class Program { public static IList GetList(string className) { Type classType = Type.GetType(className); Type listType = typeof(List<>).MakeGenericType(classType); return Activator.CreateInstance(listType) as IList; } public static void Main() { IList dogList = GetList("Test.Dog");//一定要在类型名前面加上命名空间 dogList.Add(new Dog()); try { dogList.Add(new Cat());//出错,因为dogList是List<Dog>类型,不能添加Cat } catch (Exception ex) { Console.WriteLine(ex); } IList catList = GetList("Test.Cat");//一定要在类型名前面加上命名空间 catList.Add(new Cat()); try { catList.Add(new Dog());//出错,因为catList是List<Cat>类型,不能添加Dog } catch (Exception ex) { Console.WriteLine(ex); } } } public class Dog { } public class Cat { } }
- 已建议为答案 ThankfulHeartModerator 2014年5月2日 6:27
- 已标记为答案 Barry WangModerator 2014年5月2日 8:54
-
我知道一个class的名称 比如 "Dog"
我想这样子用 List<"Dog">
我要如何做啊ASP.NET Forum
Other Discussion Forums
FreeRice Donate
Issues to report
Free Tech Books Search and Download