0

我有以下内容:

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();
        Console.WriteLine(p.writeOutput(3, new myDelegate(x => x*x)));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
    private string writeOutput(int x, myDelegate del) {
        return string.Format("{0}^2 = {1}",x, del(x));
    }
}

是否需要上述方法writeOutput?可以在没有 , 的情况下重写以下内容writeoutput以输出与上述相同的内容吗?

可以修改该行Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));以便将 3 输入到函数中吗?

class Program {

    delegate int myDelegate(int x);

    static void Main(string[] args) {

        Program p = new Program();

        Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
}
4

3 回答 3

1

显然不能这样写。想一想:第二个代码中x的值是多少?您创建了委托的实例,但是何时调用?

使用此代码:

myDelegate myDelegateInstance = new myDelegate(x => x * x);
Console.WriteLine("x^2 = {0}", myDelegateInstance(3));
于 2013-02-03T13:37:39.397 回答
1

你真的不需要一个代表。但是为了工作,您需要更改此行:

    Console.WriteLine("x^2 = {0}", new myDelegate(x => x*x));

有了这个:

    Console.WriteLine("{0}^2 = {1}", x, x*x);
于 2013-02-03T13:38:47.677 回答
1

首先,您不需要委托人。你可以直接相乘。但首先,代表的更正。

myDelegate instance = x => x * x;
Console.WriteLine("x^2 = {0}", instance(3));

您应该将委托的每个实例都视为一个函数,就像您在第一个示例中所做的那样。new myDelegate(/* blah blah */)没有必要。您可以直接使用 lambda。

我假设您正在练习使用委托/lambda,因为您可以这样写:

Console.WriteLine("x^2 = {0}", 3 * 3);
于 2013-02-03T16:24:55.413 回答