2015-04-23 115 views
2

嗨,我正在学习使用Lambda从书中。我从书上抄VS2010一段代码后,我得到了错误:C#表达式Lambda

Delegate ' System.Func<float> ' does not take 1 arguments"

VS2010标记在第3行左括号下的错误,“浮动X”之前。你能告诉我什么是错的吗?

static void Main(string[] args) 
{ 
    Func<float> TheFunction = (float x) => 
    { 
     const float A = -0.0003f; 
     const float B = -0.0024f; 
     const float C = 0.02f; 
     const float D = 0.09f; 
     const float E = -0.5f; 
     const float F = 0.3f; 
     const float G = 3f; 
     return (((((A * x + B) * x + C) * x + D) * x + E) * x + F) * x + G; 
    }; 

    Console.Read(); 
} 

回答

9

你试图写一个接受一个float输入,并回报一个float输出功能。这是一个Func<float, float>。 (举个更清晰的例子,如果你想委托有int参数和float返回类型,这将是一个Func<int, float>

一个Func<float>就没有参数,并float返回类型。从Func<TResult>文档:

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

public delegate TResult Func<out TResult>() 
+0

因为你看起来有点缺乏代表+1 –

+2

@Garry你投票回答问题,而不是书。 –

4

由于Func<T>表示代表其返回T类型的值。从MSDN

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

你想要的是一个Func<float, float> —是,它接受一个float作为参数返回float类型的值的委托。

0

在函数求最后一个参数是返回类型,其他都是参数类型。对于使用a,b,c作为参数的Func,a和b是参数类型,c是返回类型。

Func<int, int, double> func = (a,b) => a + b; 
int aInt = 1; 
int bInt = 2; 
double answer = func(aInt, bInt); // answer = 3