简体   繁体   English

关于委托实例化的一个简单问题

[英]A simple question about delegate instantiation

I am trying to read some code on the internet, but still cannot figure it out.我试图在互联网上阅读一些代码,但仍然无法弄清楚。

The code is:代码是:

private delegate string GetAString();

static void Main()
{
    int x = 40;

    GetAString firstStringMethod = new GetAString(x.ToString);

    Console.WriteLine(firstStringMethod());
} 

My question is "delegate string GetAString()" does not need parameters, but when it is instantiated, it has the x.ToString parameter.我的问题是“委托字符串GetAString()”不需要参数,但是当它被实例化时,它有x.ToString参数。

Why?为什么? Can anyone explain this?谁能解释一下? Thanks.谢谢。

A delegate is a special type of variable that can hold a reference to a method (not the result of the method but the method itself), allowing it to be passed around and invoked in places where you perhaps don't have access to the object the method belongs to.委托是一种特殊类型的变量,可以保存对方法的引用(不是方法的结果,而是方法本身),允许在您可能无法访问对象的地方传递和调用它该方法属于。

From the docs :文档

Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class.代表一个委托,它是一种数据结构,引用静态方法或类实例和该类的实例方法。

Your code:您的代码:

GetAString firstStringMethod = new GetAString(x.ToString);

Note the lack of () at the end of x.ToString .注意x.ToString末尾缺少() We're not calling x.ToString() here.我们没有在这里调用x.ToString() We're creating a GetAString and passing x.ToString (which is a method that satisfies the signature required by the delegate).我们正在创建一个GetAString并传递x.ToString (这是一种满足委托所需签名的方法)。

This means that when we call firstStringMethod() it will call x.ToString() and proxy the result to you.这意味着当我们调用firstStringMethod()它会调用x.ToString()并将结果代理给您。

Consider another example:考虑另一个例子:

public delegate int Operation(int a, int b);

We could define multiple methods:我们可以定义多种方法:

public int Sum(int a, int b)
{
    return a + b;
}

public int Multiply(int a, int b)
{
    return a * b;
}

And then switch according to user input:然后根据用户输入切换:

Operation o;
switch (Console.ReadLine())
{
    case "+":
        o = new Operation(Sum);
        break;
    case "*":
        o = new Operation(Multiply);
        break;
    default:
        Console.WriteLine("invalid operation");
        return;
}

Console.WriteLine(o(4, 3));

If the user inputs "+" then the result will be 7, while inputting "*" will result in "12".如果用户输入“+”,则结果为 7,而输入“*”则为“12”。

You can see from this example that we're not passing the arguments of Sum or Multiply when we instantiate o .你可以从这个例子中看到,当我们实例化o时,我们没有传递SumMultiply的参数。 We're simply passing the method.我们只是传递方法。 We then use the delegate to supply the arguments and get the result.然后我们使用委托来提供参数并获得结果。

Example if user input is +如果用户输入是 + 的示例

Example if user input is *如果用户输入是 * 的示例

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

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