为什么委托在静态方法中使用时不能引用非静态方法?

为什么在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; } } 

这不是必需的”。 但是您的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; } } 

你的函数需要是静态的,因为你是从静态方法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; } } 

在这种情况下,因为您没有创建任何类的实例,所以唯一的替代方法是静态函数。 如果要实例化Program类型的对象,则可以使用实例方法。

代表们基本上遵循与方法相同的规则。 在提供的示例中,您的委托必须是静态的,因为您是从静态方法调用它。 同样,这不起作用:

 static void Main(string[] args) { int Res = Add(3, 4); Console.WriteLine(Res); } public int Add(int a, int b) { int result; result = a + b; return result; } 

但是,如果您将事物移动到非静态上下文中,如下所示:

 class MyClass { public MyClass() { Fun F1 = new Fun(Add); int Res = F1(2, 3); Console.WriteLine(Res); } public int Add(int a, int b) { int result; result = a + b; return result; } } 

您可以拥有一个非静态方法的委托。

无需创建静态方法来传递委托。

但是非静态方法应该在不同的类中声明,并且必须使用该类的实例进行访问。

DelegateName DN = new DelegateName(类的实例。方法名称)