Van*_*ing 4 c# delegates dynamic anonymous-delegates
我想知道是否有可能使变量的"动态"类型适用于匿名委托.
我尝试过以下方法:
dynamic v = delegate() {
};
Run Code Online (Sandbox Code Playgroud)
但后来我收到以下错误消息:
Cannot convert anonymous method to type 'dynamic' because it is not a delegate type
不幸的是,以下代码也不起作用:
Delegate v = delegate() {
};
object v2 = delegate() {
};
Run Code Online (Sandbox Code Playgroud)
如果我想创建一个接受任何类型的委托的方法,即使是内联声明的委托,我该怎么办?
例如:
class X{
public void Y(dynamic d){
}
static void Main(){
Y(delegate(){});
Y(delegate(string x){});
}
}
Run Code Online (Sandbox Code Playgroud)
这有效,但看起来有点奇怪.你可以给它任何委托,它将运行它并返回一个值.
您还需要指定匿名方法签名在某些时候,为了让编译器做它的任何意义,因此有必要指定Action<T>或Func<T>或什么的.
static void Main(string[] args)
{
Action d = () => Console.WriteLine("Hi");
Execute(d); // Prints "Hi"
Action<string> d2 = (s) => Console.WriteLine(s);
Execute(d2, "Lo"); // Prints "Lo"
Func<string, string> d3 = (s) =>
{
Console.WriteLine(s);
return "Done";
};
var result = (string)Execute(d3, "Spaghettio"); // Prints "Spaghettio"
Console.WriteLine(result); // Prints "Done"
Console.Read();
}
static object Execute(Delegate d, params object[] args)
{
return d.DynamicInvoke(args);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2216 次 |
| 最近记录: |