[英]How to chose the “right” constructor for Activator.CreateInstance
當使用.NET的Activator.CreateInstance
方法時,我傳遞了它的構造函數的類型和參數。 有些類型有這樣的幾個構造函數:
public foo(Status status, TServiceReference listService,
Int32 listID, Int16 clientID)
{
Status = status;
ListService = listService;
ListID = listID;
ClientID = clientID;
}
public foo(Status status, String listServiceRegexCompare,
Int32 listID, Int16 clientID)
{
Status = status;
ListServiceRegexCompare = listServiceRegexCompare;
ListID = listID;
ClientID = clientID;
}
如果在運行時第二個參數為null
,我總是希望選擇構造函數1。 有什么辦法可以實現嗎? (注意我正在為幾種不同的類型調用Activator.CreateInstance
,而對於另一種類型,構造函數可能期望另外計算不同類型的參數)。 但是我總是想要一個不期望調用字符串的構造函數,並為該參數傳遞一個null對象。
謝謝。
編輯:
我正在調用這樣的方法
public void ActivateEvent(Object instance, EventInfo eventInfo,
ILoggingSupport logger, params Object[] parameter)
{
Delegate handler =
Delegate.CreateDelegate(
eventInfo.EventHandlerType, this,
GetType().GetMethod("Handler"));
_instance = instance;
_eventInfo = eventInfo;
_handler = handler;
_logger = logger;
eventInfo.AddEventHandler(instance, handler);
Type eventArgsType =
eventInfo.EventHandlerType.GetGenericArguments()[0];
_referenceArgs =
Activator.CreateInstance(eventArgsType, parameter) as IComparable;
}
首先,從初始化類的方法來看,你有兩個稍微不同的類版本,你已經合並為一個。 即具有服務引用和具有正則表達式的引用。 如果是這種情況(服務引用和正則表達式是相互排斥的),您應該考慮將它們重寫為具有公共基類的兩個獨立類。 如果你這樣做,那么這個問題就會消失。
在您調用CreateInstance的代碼中,您有一個非常通用的代碼片段,並且嘗試解決通用代碼中的特定問題將很難。 代碼不再是通用的。 您可以做的是嘗試在通話之前解決它。 例如,根據您需要支持的參數數量,有一些過載
public void ActivateEvent<T1,T2>(Object instance, EventInfo eventInfo,
ILoggingSupport logger, T1 p1, T2 p2)
{
...
var parameterTypes = new []{typeof(T1), typeof(T2)};
var arguments = new object[]{p1,p2};
var ctor = eventArgsType.GetConstructor(parameterTypes);
_referenceArgs = ctor.Invoke(arguments) as IComparable;
}
那不是使用Activator.CreateInstance
因為當您將null參數向上轉換為object時,將刪除所需的類型信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.