![](/img/trans.png)
[英]Creating a Generic Method for Accepting Type Object and return a new Object of Type
[英]Need a type safe method of creating object
string attribute = doc.SelectSingleNode("/class/@name").Value.ToString();
ObjectHandle employee = Activator.CreateInstance("EmployeeData", attribute);
Object employeeObject = employee.Unwrap();
return employeeObject;
“ EmployeeData”是當前執行的程序集。 從XML文件的入口節點選擇屬性。 我需要以一種更類型安全的方式創建和返回對象,而不使用ObjectHandle和UnWrap()。 有人可以幫忙嗎?
聽起來這可以完成工作:
var type = Assembly.GetExecutingAssembly().GetType(attribute);
return Activator.CreateInstance(type);
使用CreateInstance(Type)
重載可確保定義類型的程序集已經加載,因此重載可以自由返回一個直object
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.