是否有一种方法可以基于我在运行时知道类的名称这一事实来创建类的实例。基本上,我将类名放在字符串中。
当前回答
要从解决方案中的另一个项目中创建类的实例,您可以获得由任何类的名称指示的程序集(例如BaseEntity)并创建一个新实例:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");
其他回答
我知道我来晚了……但是,您正在寻找的解决方案可能是上述方法的结合,并使用接口定义对象的公共可访问方面。
然后,如果以这种方式生成的所有类都实现了该接口,则可以将其转换为接口类型并使用结果对象。
看看激活器。CreateInstance除外的方法。
我曾经成功地使用过这个方法:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
您需要将返回的对象强制转换为所需的对象类型。
要从解决方案中的另一个项目中创建类的实例,您可以获得由任何类的名称指示的程序集(例如BaseEntity)并创建一个新实例:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");
For instance, if you store values of various types in a database field (stored as string) and have another field with the type name (i.e., String, bool, int, MyClass), then from that field data, you could, conceivably, create a class of any type using the above code, and populate it with the value from the first field. This of course depends on the type you are storing having a method to parse strings into the correct type. I've used this many times to store user preference settings in a database.
推荐文章
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空
- c#中有任何连接字符串解析器吗?
- 在Linq中转换int到字符串到实体的问题