簡體   English   中英

在C#中按類名稱按字符串獲取類屬性

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM