我正在查看 C# 5 in a Nutshell
文本,关于委托(delegate)参数兼容性的部分。它说
When you call a method, you can supply arguments that have more specific types than the parameters of that method. This is ordinary polymorphic behavior. For exactly the same reason, a delegate can have more specific parameter types than its method target. This is called contravariance.
这段话到最后一句话都说得通。为什么是逆变,即这里的投影是逆变的?
示例如下。
delegate void StringAction (string s);
class Test
{
static void Main()
{
StringAction sa = new StringAction (ActOnObject);
sa ("hello");
}
static void ActOnObject (object o)
{
Console.WriteLine (o); // hello
}
}
最佳答案
object
(函数 ActionObject
的参数)到为委托(delegate)声明的类型(string
)的投影是逆变的。
这是允许的,因为通过给它传递一个字符串(由于委托(delegate)签名,你必须这样做),你保证你将有一个 object
(分配的函数采用),所以一切都是漂亮又安全。
如你所知,“普通多态性”在这种情况下实际上称为协方差。
参见 MSDN更多细节。
关于c# - 委托(delegate)逆变(参数兼容性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858925/