简体   繁体   English

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

[英]Get class properties by class name as string in C#

Can I get class properties if i have class name as string? 如果我将类名作为字符串,是否可以获取类属性? My entities are in class library project and I tried different methods to get type and get assembly but i am unable to get the class instance. 我的实体在类库项目中,我尝试了不同的方法来获取类型和获取程序集,但是我无法获取该类实例。

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

nothing is working 没有任何工作

I suspect you're looking for: 我怀疑您在寻找:

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

Note: 注意:

  • This will only look in mscorlib and the currently executing assembly unless you also specify the assembly in the name 除非您在名称中指定了程序集,否则它将仅在mscorlib和当前正在执行的程序集中查找
  • It needs to be a namespace-qualified name, eg MyProject.User 它必须是一个名称空间限定的名称,例如MyProject.User

EDIT: To access a type in a different assembly, you can either use an assembly-qualified type name, or just use Assembly.GetType , eg 编辑:要访问其他程序集中的类型,可以使用程序集限定的类型名称,也可以只使用Assembly.GetType ,例如

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

(Note that I haven't addressed getting properties as nothing else in your question talked about that. But Type.GetProperties should work fine.) (请注意,我没有解决获取属性的问题,因为您的问题中没有其他谈论这个问题。但是Type.GetProperties应该可以正常工作。)

Can I get class properties if i have class name as string? 如果我将类名作为字符串,是否可以获取类属性?

Of course: 当然:

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

This will get a list of public instance properties. 这将获得公共实例属性的列表。 If you need to access private or static properties you might need to indicate that: 如果您需要访问私有或静态属性,则可能需要指出:

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

尝试

Type type = Type.GetType("Assembly with namespace");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM