Ash*_*ohn 7 c# delegates covariance
请考虑以下代码段
namespace ConsoleApplication1
{
public delegate TResult Function<in T, out TResult>(T args);
class Program
{
static void Main(string[] args)
{
Program pg =new Program();
Function<Object, DerivedClass> fn1 = null;
Function<String, BaseClass> fn2 = null;
fn1 = new Function<object, DerivedClass>(pg.myCheckFuntion)
fn2=fn1;
fn2("");// calls myCheckFuntion(Object a)
pg.myCheckFuntion("Hello"); //calls myCheckFuntion(String a)
}
public DerivedClass myCheckFuntion(Object a)
{
return new DerivedClass();
}
public DerivedClass myCheckFuntion(String a)
{
return new DerivedClass();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么委托调用和普通方法调用调用不同的方法.
委托myCheckFuntion(Object)在编译时受到约束- 你告诉它找到一个接受一个的方法Object.该绑定仅适用于单个方法 - 它不会在执行时根据实际参数类型执行重载解析.
当你调用pg.myCheckFuntion("Hello") 该会结合myCheckFuntion(String)在编译时间,因为"Hello"是一个字符串,并从串来串转换优于从字符串转换在重载决议提出异议.
请注意,如果你写:
object text = "Hello";
pg.myCheckFuntion(text);
Run Code Online (Sandbox Code Playgroud)
那么这将调用myCheckFuntion(Object).