简体   繁体   English

如果使用委托,我需要那些方法是静态的吗?

[英]If I use Delegates, I need those methods to be static?

I have a C# code like this: 我有这样的C#代码:

using System;
delegate int anto(int x);
class Anto 
{
    static void Main()
    {
        anto a = square;
        int result = a(3);
        Console.WriteLine(result);
    }
    static int square(int x)
    {
        return x*x;
    }
}

which output's : 9 . 哪个输出: 9 Well I'm a novice in C#, so I started to play around with this code and so when I remove the static keyword from the square method, then I'm getting error like this: 好吧,我是C#的新手,所以我开始尝试这段代码,因此当我从square方法中删除static关键字时,我会收到如下错误:

An object reference is required to access non-static member `Anto.square(int)'
Compilation failed: 1 error(s), 0 warnings

what causes this error? 是什么导致此错误? So if I use delegates I need the method to be static ? 所以,如果我使用delegates我需要方法是static吗?

I run this code here 我在这里运行这段代码

Thanks in advance. 提前致谢。

Because Main is static, it can only reference other static members. 因为Main是静态的,所以它只能引用其他静态成员。 If you remove static from square , it becomes an instance member, and in the static context of Main , there is no instance of any object, so instance members aren't 'valid'. 如果从square移除static ,它将成为实例成员,并且在Mainstatic上下文中,没有任何对象的实例,因此实例成员不是“有效的”。

Thankfully there's nothing crazy going on with delegates, it's just the way static works - it indicates members are global to a type and not an instance of that type. 幸运的是,委托没有什么疯狂的事情,这只是static工作的方式-它指示成员是某个类型的全局成员,而不是该类型的实例。

It's required to be static because it's used in a static method. 它必须是静态的,因为它是在静态方法中使用的。 You'd need an instance of Anto to make your example work. 您需要一个Anto实例才能使示例工作。

var myAnto = new Anto();
anto a = myAnto.square;

This is untested and may not compile based on the protection level of Anto.square . 这未经测试,可能无法根据Anto.square的保护级别进行Anto.square

It doesn't need to be static. 不需要是静态的。 You can assign a non-static method to a delegate, but if it is non-static then you need to instatiate an object of type Anto : 您可以将非静态方法分配给委托,但是如果它是非静态方法,则需要实例化Anto类型的对象:

Anto anto = new Anto();
anto a = anto.square;

It's rather pointless here though since the method doesn't access any of the instance members. 但是,由于该方法不访问任何实例成员,因此在这里毫无意义。 It makes more sense that it is static. 它是静态的更有意义。

Static methods may be called from before creating an instance, you must be a static method. 静态方法可能是从创建实例之前调用的,您必须是静态方法。

Can be written as follows, if necessary 必要时可以写成如下形式

anto a = (x)=>x*x ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM