从字符串变量创建对类的引用

时间:2015-10-15 07:25:42

标签: c# .net

这是我需要做的事情;

string className = "Customer";
List<className> myList = new List<className>();

className可以是我的任何Entity Framework类。我以客户为例。

我希望这是可能的。如果是这样,怎么样?

更新:

我还需要使用此方法从实体框架dbContext中检索数据。例如......

        string className = "Customer";
        var myData = db.Set<className>();

对不起。不知道我是否应该在这里创建另一个问题或更新这个问题。对我温柔。我是新来的。 :O)

2 个答案:

答案 0 :(得分:4)

如果你想在这种情况下可以使用反射,但我会考虑另一种解决方案。

Type type = Type.GetType("Namespace.ClassName");
Type listType = typeof(List<>).MakeGenericType(new [] { type } );
IList list = (IList)Activator.CreateInstance(listType);

答案 1 :(得分:1)

您可以使用:

Type customerType = Type.GetType("this.is.a.namespace.Customer");

相关:other question