为什么在 C# 中使用委托(delegate)时需要将函数设为 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;
}
}
最佳答案
这不是“必要的”。但是您的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;
}
}
关于c# - 为什么委托(delegate)在静态方法中使用时不能引用非静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2298997/