在第一個示例中是剛剛在封面下完成的演員嗎?
是的,你可以這麼說!
Combine
方法是在沒有泛型C#的.NET 1中編寫的。因此的Combine
正式返回類型必須是Delegate
:
public static Delegate Combine(Delegate a, Delegate b)
{
...
}
但該方法又返回Action
當兩個a
和b
是Action
。是的,要求a
和b
具有相同的運行時類型。
請不要寫MulticastDelegate.Combine
作爲Combine
是由System.Delegate
類定義的static
方法。因此請說Delegate.Combine
,這不太令人困惑。
迂迴:
C#的當前版本和Combine
與逆變委託類型的問題。考慮以下幾點:
Action<string> doSomethingToString; // will be assigned below
Action<ICloneable> a = cloneable => { Console.WriteLine("I'm cloning"); cloneable.Clone(); }
Action<IConvertible> b = convertible => { Console.WriteLine("I'm converting"); convertible.ToInt32(CultureInfo.InvariantCulture); }
Action<string> aStr = a; // OK by contravariance of Action<in T>, aStr and a reference same object
Action<string> bStr = b; // OK by contravariance of Action<in T>, bStr and b reference same object
doSomethingToString = aStr + bStr; // throws exception
doSomethingToString("42"); // should first clone "42" then convert "42" to Int32
現在,假設未來的某個框架的版本中引入的通用Combine
方法:
public static TDel Combine<TDel>(TDel a, TDel b) where TDel : Delegate
{
// use typeof(TDel) to figure out type of new "sum" delegate
}
,並假設C#改爲使得+
被翻譯成調用新的通用Combine<>
方法,然後逆變和代表組合將被修復!我想他們告訴我們他們有更高的優先級,但仍然。
執行財產以後會不會有每個委託類型定義了自己的靜態'Combine'方法的任何根本問題?然後,如果兩個代表'X'和'Y'都是可替代'FooDelegate'的類型,則可以使用'FooDelegate.Combine(X,Y)'。即使沒有協變問題,它看起來比'(FooDelegate)Delegate.Combine(X,Y)'更清潔,並且可以添加一個編譯時檢查'X'和'Y'是合適的。 – supercat
@supercat對我來說,這聽起來像一個很好的解決方案。 –