在第一个示例中是刚刚在封面下完成的演员吗?
是的,你可以这么说!
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对我来说,这听起来像一个很好的解决方案。 –