如何使用变体委托实现参数到参数的隐式转换?

How do I achieve implicit conversion of an argument to a parameter using a variant delegate?

我想将参数隐式转换为参数,而不是使用类型转换显式转换参数。参数的派生程度低于参数,因此我希望使用逆变委托将参数隐式转换为参数。但是,编译器仍然抱怨我需要将“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)
{

}

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

当你这样做时:

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);