Sun*_*has 7 .net c# delegates visual-studio-2005 function
为什么在C#中使用委托时需要使用STATIC函数?
class Program
{
delegate int Fun (int a, int b);
static void Main(string[] args)
{
Fun F1 = new Fun(Add);
int Res= F1(2,3);
Console.WriteLine(Res);
}
**static public int Add(int a, int b)**
{
int result;
result = a + b;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
Ðаn*_*Ðаn 12
这不是必需的".但是你的Main方法是static,所以它不能调用非static方法.尝试这样的事情(这不是一个很好的做事方式 - 你真的应该创建一个新的类,但它不会更改你的样本):
class Program
{
delegate int Fun (int a, int b);
void Execute()
{
Fun F1 = new Fun(Add);
int Res= F1(2,3);
Console.WriteLine(Res);
}
static void Main(string[] args)
{
var program = new Program();
program.Execute();
}
int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
你的函数需要是静态的,因为你是从静态方法Main调用的.您可以使方法非静态:
class Program
{
delegate int Fun (int a, int b);
static void Main(string[] args)
{
Program p = new Program(); // create instance of Program
Fun F1 = new Fun(p.Add); // now your non-static method can be referenced
int Res= F1(2,3);
Console.WriteLine(Res);
}
public int Add(int a, int b)
{
int result;
result = a + b;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21586 次 |
| 最近记录: |