最初のサンプルでは、カバーの下でキャストが行われていますか?
はい、そう言えます!
このCombine
メソッドは、汎用 C# が存在しない .NET 1 で作成されました。したがって、 の正式な戻り値の型は次のCombine
ようにする必要がありましたDelegate
。
public static Delegate Combine(Delegate a, Delegate b)
{
...
}
ただし、このメソッドは、とのAction
両方が である場合でもを返します。はい、同じランタイム タイプである必要があります。a
b
Action
a
b
クラスで定義されたメソッドをMulticastDelegate.Combine
そのまま書かないでください。したがって、混乱が少ないと言えます。Combine
static
System.Delegate
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<>