[英]How to use class name as parameter in C#
我想要做的是自動創建一些對象。
例如,在Java中,類可以作為參數傳遞
Class A{
}
Object createObjectBy(class clazz){
// .. do construction work here
}
when using it, just ---> createObjectBy(A.class)
這對很多事情都有好處。
所以,我怎么能在C#做類似的事情?
Object createObjectBy(Type clazz){
// .. do construction work here
Object theObject = Activator.CreateInstance(clazz);
return theObject;
}
用法:
createObjectBy(typeof(A));
或者您可以直接使用Activator.CreateInstance
:-)
理想的方法是使用泛型
public static T CreateInstance<T>() where T: new()
{
// Do some business logic
Logger.LogObjectCreation(typeof(T));
// Actualy instanciate the object
return new T();
}
一個電話示例看起來像
var employee = CreateInstance<Employee>();
如果對象的類型在運行時是未知的,例如通過插件系統,則需要使用Type
類:
public static object CreateInstance(Type type)
{
// Do some business logic
Logger.LogObjectCreation(type);
// Actualy instanciate the object
return Activator.CreateInstance(type);
}
一個電話示例看起來像
var instance = CreateInstance(someType);
當然,除了使用關鍵字new
之外,沒有任何東西能夠實現對象的實現。 除了可能不是實例化,而是重用一個對象,比如通過緩存。
如果你必須解決類型未知的第二種方法,那么Activator.CreateInstance
有一些替代方法 。 雖然文章推薦使用lambda表達式,但您最大的考慮因素是:
如果您只需要創建一次對象,只需堅持使用Activator.CreateInstance方法即可。 如果您需要在短時間內多次創建它,請嘗試lambda方法。 最后一種方法類似於編譯的正則表達式與即時正則表達式。
使用類Type。 您可以通過調用返回它的實例
obj.GetType();
或沒有對象實例
typeof(className);
我希望它有所幫助。
C#不支持此功能。 但是你想做什么?
你可能會使用:
createObjectBy(Type type);
要么
createObjectBy<T>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.