[英]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.