[英]Get class properties by class name as string in C#
如果我将类名作为字符串,是否可以获取类属性? 我的实体在类库项目中,我尝试了不同的方法来获取类型和获取程序集,但是我无法获取该类实例。
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);
没有任何工作
我怀疑您在寻找:
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
应该可以正常工作。)
如果我将类名作为字符串,是否可以获取类属性?
当然:
var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
这将获得公共实例属性的列表。 如果您需要访问私有或静态属性,则可能需要指出:
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.