手動您可以做到這一點,但它與轉換過程中涉及的反射一樣昂貴。一旦委託轉換它的行爲基本上是相同的......
internal class Program
{
//An example delegate target
static void Click(object o, EventArgs e) { }
//A simple test method
static void Main(string[] args)
{
EventHandler onclick = Click;
EventHandler<EventArgs> converted;
if (!TryConvertDelegate(onclick, out converted))
throw new Exception("failed");
}
//The conversion of one delegate type to another
static bool TryConvertDelegate<TOldType, TNewType>(TOldType oldDelegate, out TNewType newDelegate)
where TOldType : class, System.ICloneable, System.Runtime.Serialization.ISerializable
where TNewType : class, System.ICloneable, System.Runtime.Serialization.ISerializable
{
if (!typeof(Delegate).IsAssignableFrom(typeof(TOldType)) || !typeof(Delegate).IsAssignableFrom(typeof(TNewType)))
throw new ArgumentException(); //one of the types is not a delegate
newDelegate = default(TNewType);
Delegate handler = oldDelegate as System.Delegate;
if (handler == null)
return true; //null in, null out
Delegate result = null;
foreach (Delegate d in handler.GetInvocationList())
{
object copy = System.Delegate.CreateDelegate(typeof(TNewType), d.Target, d.Method, false);
if (copy == null)
return false; // one or more can not be converted
result = System.Delegate.Combine(result, (System.Delegate)copy);
}
newDelegate = result as TNewType;
return (newDelegate != null);
}
你的解釋是偉大的工作,直到我試圖用行動。我如何處理Action? (Action formatMessageCallback) 我的方法簽名: public void Error –
我不公開Common.Logging委託或任何API,因爲我們決定在將來使用不同的日誌記錄框架。如果發生這種情況,那麼我們所要做的就是編寫一些代碼,這些代碼實現了我們之前定義的日誌接口,並將這些調用包裝到新的日誌框架中。 –
@大衛:沒有使用記錄器的委託的原因是有效的,謝謝解釋。請參閱更新以獲取您的第一條評論的解決方案。 –