在C#中按类名获取类属性作为字符串

时间:2013-02-20 11:20:10

标签: c# reflection .net-assembly

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

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);

没有任何工作

3 个答案:

答案 0 :(得分: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应该可以正常工作。)

答案 1 :(得分:1)

  

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

当然:

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

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

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

答案 2 :(得分:0)

尝试

Type type = Type.GetType("Assembly with namespace");
相关问题