考虑下面的代码片段
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();
}
}为什么委托调用和普通方法调用调用不同的方法。
发布于 2011-07-22 22:14:17
这个委托在编译时绑定到myCheckFuntion(Object) --你告诉它去找一个接受Object的方法。该绑定只绑定到单个方法-它不会在执行时基于实际的参数类型执行重载解析。
当您调用pg.myCheckFuntion("Hello")时,它将在编译时绑定到myCheckFuntion(String),因为"Hello"是一个字符串,并且在重载解析中,从字符串到字符串的转换优先于从字符串到对象的转换。
请注意,如果您编写:
object text = "Hello";
pg.myCheckFuntion(text);然后它将调用myCheckFuntion(Object)。
发布于 2011-07-22 22:23:56
fn2调用myCheckFuntion(Object a)是因为它的声明:
fn1 = new Function<object, DerivedClass>(pg.myCheckFuntion)
fn2 = fn1; // here you copy the referencepg.myCheckFuntion("Hello");调用myCheckFuntion(Object a)是因为String是比object更严格的类型。
如果将字符串强制转换为Object
pg.myCheckFuntion((object)"Hello");它将调用其他方法。
发布于 2011-07-22 22:15:37
委托对象本身仍然只指向一个函数,而不是一系列函数。co(Ntra)方差仅允许您将其指向更大的函数类型域。同样,您可以为object类型的变量分配各种类型的值,但为string类型的变量分配的值更少。即使这样,一个变量在任何给定时间仍然只有一个实际类型和一个实际值。
https://stackoverflow.com/questions/6791300
复制相似问题