为什么这些打印不同的东西?
假设我有这样的课程:
public class ExampleOfFunc
{
public int Addition(Func<int> additionImplementor)
{
if (additionImplementor != null)
return additionImplementor();
return default(int);
}
}
Run Code Online (Sandbox Code Playgroud)
并在Main方法中:
这打印200:
ExampleOfFunc exampleOfFunc = new ExampleOfFunc();
Console.WriteLine("{0}", exampleOfFunc.Addition(
() =>
{
return 100 + 100;
})); // Prints 200
Run Code Online (Sandbox Code Playgroud)
但这打印Prints System.Func'1[System.Int32]:
Console.WriteLine("{0}", new Func<int>(
() =>
{
return 100 + 100;
})); // Prints System.Func`1[System.Int32]
Run Code Online (Sandbox Code Playgroud)
这条线
return additionImplementor();
Run Code Online (Sandbox Code Playgroud)
调用该函数并返回其结果,然后传递给该函数Console.WriteLine().
虽然这一行
Console.WriteLine("{0}", new Func<int>(
() =>
{
return 100 + 100;
}
));
Run Code Online (Sandbox Code Playgroud)
只是将函数传递Console.WriteLine()给它而不调用它.添加()以在打印之前执行该功能...
Console.WriteLine("{0}", new Func<int>(
() =>
{
return 100 + 100;
}
)());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |