在方法中创建委托类型 [英] Creating a delegate type inside a method
问题描述
例如:
$我想在C#里创建一个委托类型,用于创建匿名方法。 b $ b
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中执行此操作。 p>
为什么要在方法中创建委托类型?在方法之外宣布它是什么问题?基本上,你不能这样做 - 你不能在方法中声明一个类型(任何类型的类型)。
将声明.NET 3.5中存在的所有Func / Action通用代理 - 然后您可以执行以下操作:
public void MyMethod(){
Func< int,int,int> mySumImplementation =
delegate(int a,int b){return a + b; };
Console.WriteLine(mySumImplementation(1,1).ToString());
}
声明在我的 C#/。NET版本页面。
I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.
For Example :
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());
}
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.
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());
}
The declarations are on my C#/.NET Versions page.
这篇关于在方法中创建委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!