1

如果我将类名作为字符串,我可以获得类属性吗?我的实体在类库项目中,我尝试了不同的方法来获取类型和获取程序集,但我无法获取类实例。

var obj = (object)"User";
var type = obj.GetType();
System.Activator.CreateInstance(type);

object oform;
var clsName = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("[namespace].[formname]");

Type type = Type.GetType("BOEntities.User");
Object user = Activator.CreateInstance(type);

没有任何工作

4

3 回答 3

4

我怀疑你正在寻找:

Type type = Type.GetType("User");
Object user = Activator.CreateInstance(type);

笔记:

  • 这只会查看mscorlib当前正在执行的程序集,除非您还在名称中指定程序集
  • 它需要是一个命名空间限定的名称,例如MyProject.User

编辑:要访问不同程序集中的类型,您可以使用程序集限定的类型名称,或者只使用Assembly.GetType,例如

Assembly libraryAssembly = typeof(SomeKnownTypeInLibrary).Assembly;
Type type = libraryAssembly.GetType("LibraryNamespace.User");
Object user = Activator.CreateInstance(type);

(请注意,我没有解决获取属性的问题,因为您的问题中没有其他内容谈到这一点。但Type.GetProperties应该可以正常工作。)

于 2013-02-20T11:22:00.523 回答
2

如果我将类名作为字符串,我可以获得类属性吗?

当然:

var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

这将获得公共实例属性的列表。如果您需要访问私有或静态属性,您可能需要指出:

var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties(BindingFlags.NonPublic);
于 2013-02-20T11:22:19.743 回答
0

尝试

Type type = Type.GetType("Assembly with namespace");
于 2013-02-20T11:23:35.037 回答