C# 表达式 Lambda
C# expression Lambda
您好,我正在从一本书中学习如何使用 Lambda。将书上的一段代码复制到VS2010后报错:
Delegate 'System.Func<float>
' does not take 1 arguments"
VS2010 标记了第 3 行左括号下的错误,在 "float 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();
}
因为 Func<T>
表示 returns 类型值 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
作为参数的委托和returns一个值类型 float
.
您正在尝试编写一个函数,该函数接受一个float
输入,并且returns float
输出。那是 Func<float, float>
。 (举个更清楚的例子,如果你想要一个带有 int
参数和 return 类型 float
的委托,那就是 Func<int, float>
。)
A Func<float>
没有参数,return 类型的 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>()
Func 的最后一个参数是return 类型,其他都是参数类型。对于以a、b、c为参数的Func,a、b为参数类型,c为return类型。
Func<int, int, double> func = (a,b) => a + b;
int aInt = 1;
int bInt = 2;
double answer = func(aInt, bInt); // answer = 3
您好,我正在从一本书中学习如何使用 Lambda。将书上的一段代码复制到VS2010后报错:
Delegate '
System.Func<float>
' does not take 1 arguments"
VS2010 标记了第 3 行左括号下的错误,在 "float 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();
}
因为 Func<T>
表示 returns 类型值 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
作为参数的委托和returns一个值类型 float
.
您正在尝试编写一个函数,该函数接受一个float
输入,并且returns float
输出。那是 Func<float, float>
。 (举个更清楚的例子,如果你想要一个带有 int
参数和 return 类型 float
的委托,那就是 Func<int, float>
。)
A Func<float>
没有参数,return 类型的 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>()
Func 的最后一个参数是return 类型,其他都是参数类型。对于以a、b、c为参数的Func,a、b为参数类型,c为return类型。
Func<int, int, double> func = (a,b) => a + b;
int aInt = 1;
int bInt = 2;
double answer = func(aInt, bInt); // answer = 3