在阅读了 SO 中的以下问题后,我正在研究委托差异:Delegate.CreateDelegate() and generics: Error binding to target method
我在https://www.blogger.com/comment.g?blogID=8184237816669520763&postID=2109708553230166434从 Barry kelly 那里找到了一段非常好的代码
在这里(以糖化形式:-)
using System;
namespace ConsoleApplication4
{
internal class Base
{
}
internal class Derived : Base
{
}
internal delegate void baseClassDelegate(Base b);
internal delegate void derivedClassDelegate(Derived d);
internal class App
{
private static void Foo1(Base b)
{
Console.WriteLine("Foo 1");
}
private static void Foo2(Derived b)
{
Console.WriteLine("Foo 2");
}
private static T CastDelegate<T>(Delegate src)
where T : class
{
return (T) (object) Delegate.CreateDelegate(
typeof (T),
src.Target,
src.Method,
true); // throw on fail
}
private static void Main()
{
baseClassDelegate a = Foo1; // works fine
derivedClassDelegate b = Foo2; // works fine
b = a.Invoke; // the easy way to assign delegate using variance, adds layer of indirection though
b(new Derived());
b = CastDelegate<derivedClassDelegate>(a); // the hard way, avoids indirection
b(new Derived());
}
}
}
除了这一行(看起来很简单)之外,我都了解。
b = a.调用;// 使用方差分配委托的简单方法,虽然增加了间接层
谁能告诉我:
- 如何在不传递静态函数所需的参数的情况下调用调用。
- 当您从调用调用分配返回值时,何时在幕后发生
- 巴里所说的额外间接是什么意思(在他的评论中)