创建一个方法内部的委托类型 [英] Creating a delegate type inside a method
本文介绍了创建一个方法内部的委托类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个用于创建匿名方法的目的的方法内部在C#中的委托类型
I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.
例如:
public void MyMethod(){
delegate int Sum(int a, int b);
Sum mySumImplementation=delegate (int a, int b) {return a+b;}
Console.WriteLine(mySumImplementation(1,1).ToString());
}
不幸的是,我不能这样做在.NET 2.0和C#2.0。
Unfortunately, I cannot do it in .NET 2.0 and C# 2.0.
推荐答案
你为什么要创建的方法中的委托类型?这有什么错,宣布它的方法么?基本上,你不能做到这一点 - 你不能声明的键入的(任何一种类型)的方法在
Why do you want to create the delegate type within the method? What's wrong with declaring it outside the method? Basically, you can't do this - you can't declare a type (any kind of type) within a method.
一种选择。将申报所有的功能/动作一般代表是存在于.NET 3.5 - 那么你可能只是这样做:
One alternative would be to declare all the Func/Action generic delegates which are present in .NET 3.5 - then you could just do:
public void MyMethod(){
Func<int, int, int> mySumImplementation =
delegate (int a, int b) { return a+b; };
Console.WriteLine(mySumImplementation(1,1).ToString());
}
该声明是在我的 C#/。NET版本页面。
这篇关于创建一个方法内部的委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文