首页 > 解决方案 > 如何使用变体委托实现参数到参数的隐式转换?

问题描述

我想将参数隐式转换为参数,而不是使用类型转换显式转换参数。参数的派生程度低于参数,因此使用逆变委托我希望参数隐式转换为参数。但是,编译器仍然抱怨我需要将“object”显式转换为“string”。

public static void Main()
{
DDoSomething<string> doSomething = DoSomething;

object obj = "text";

doSomething(obj);
}

public delegate void DDoSomething<in A>(A str);

public static void DoSomething(string str)
{

}

标签: c#delegates

解决方案


您不能调用需要带有对象的字符串的方法,或者更一般地说,您不能使用基实例代替派生实例。

当你这样做时:

DDoSomething<string> doSomething = DoSomething;

doSomething现在实际上是具有此签名的方法:void (string).

逆变适用于委托实例本身,而不是参数:

public static void Main()
{
    DDoSomething<object> doSomething = (object obj) => Console.WriteLine(obj);
    
    DDoSomething<string> doSomethinString = doSomething;
    // Using a DDoSomething<object> in place of DDoSomething<string> is legal because of "in"

    doSomethinString("text");
    // This is safe because string is used in place of object (derived in place of base)
}

public delegate void DDoSomething<in A>(A str);

推荐阅读