我知道如何使用Action和Func在.NET中,但每次我开始,使用我调用的常规旧方法可以实现完全相同的解决方案.
这排除了当一个Action或者Func被用作我无法控制的东西的参数时,比如LINQ .Where.
基本上我的问题是......为什么这些存在?他们给了我什么额外的和新的一个简单的方法不?
我写了一个看起来像这样的代码:
Thread t = new Thread(() => createSomething(dt, start, finish) );
t.Start();
Run Code Online (Sandbox Code Playgroud)
它有效(有时几乎感觉有多个线程).
但我不使用任何代表.
我仍然想知道为什么我可以将 lambda 表达式传递给接受 Action 类型参数的方法,
而我不能将 lambda 表达式传递给接受 Delegate 类型参数的
方法我有这个 Print 方法,我将使用 action 和代表
public static void Print()
{
Console.WriteLine("Printing ..");
}
Run Code Online (Sandbox Code Playgroud)
我创建了这两个方法,它们将调用 Print 方法,因为您可以看到第一个具有操作类型参数,第二个具有委托类型参数这些参数将引用方法“打印”
public static void ActionParamMethod(Action DAction)
{
DAction();
}
public static void DelegateParamMethod(Delegate SomeDelegate)
{
}
Run Code Online (Sandbox Code Playgroud)
我将把 lambda 表达式传递给这些方法
public static void SomeHowMethod()
{
DelegateParamMethod(() => Print());
ActionParamMethod(() => Print());
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将 lambda 表达式传递给接受 Delegate 参数的方法时,我收到此错误
无法将 lambda 表达式转换为类型“System.Delegate”,因为它不是委托类型
为什么它不是委托类型而 Action 是委托类型?
为什么我可以将 lambda 表达式传递给接受 Action 参数的方法,但我不能将 lambda 表达式传递给接受 Delegate 参数的方法?
为新手提出的问题提前道歉(因为我是C#中的一员):
在研究代表时,在我看来,关键字的整个"功能" 的组合Action和Func覆盖delegate.
换句话说,您无法对delegate关键字执行任何操作,但无法使用Action或关键字Func.
我尝试过以下示例(工作正常):
Func<int,int,int,int> func = (x,y,z) => (x<<9)|(y<<6)|(z<<3);
Action<int,int,int> action = (x,y,z) => Console.WriteLine(x|y|z);
Run Code Online (Sandbox Code Playgroud)
我错了吗?如果是,那么请您提供一个反例吗?