简体   繁体   中英

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
  • It needs to be a namespace-qualified name, eg 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 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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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