c# - 将 Action 委托(delegate)作为参数传递给构造函数时出现参数错误

标签 c# delegates

我正在尝试将 Action 委托(delegate)传递给构造函数但出现以下错误:

Delegate 'Action' does not take 0 arguments

代码:

public sealed class VariantProcessor
{
    private string _myAppConnectionString { get; set; }
    private readonly Action<Variant> _transform;
    public Variant(string _myAppConnectionString,Action<Variant> transform)
    {
         _myAppConnectionString = _myAppConnectionString;
         _transform = transform;
    }
    public void Process(Variant model)
    {
        try
        {
            _transform(model);
             //version creation shared by both the derived types
        }
        catch (Exception) 
        {
        }
    }
}

public class AggregateCalculator : IVariantProcessor
{
    private string _myAppConnectionString { get; set; }
     public void Process(Variant model)
     {
            _myAppConnectionString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
            new VariantProcessor( _myAppConnectionString,
               () => Transform(model) //error
               );
     }
    private void Transform(Variant model)
    {
        //logic on variant model
    }
}

我也这样试过,但还是不行:

new VariantProcessor(_myAppConnectionString,
                   Transform(model) // error
                    );

实际上我在理解这种语法 () => Transform(model) 时遇到了问题,因此我不知道这里有什么问题。

谁能帮我弄清楚这里的问题是什么?

最佳答案

Action您的构造函数采用的是 Action<Variant>这意味着它是一段代码,它接受一个类型为 Variant 的参数。并返回 void(因为 Action 不返回任何内容。

当您调用构造函数时,您可以向它传递一个带有单个参数的 lambda,如下所示:

new VariantProcessor(_myAppConnectionString, model => Transform(model));

或者您可以将接受 Variant 的函数的名称传递给它并返回 void :

new VariantProcessor(_myAppConnectionString, Transform);

语法:

() => Transform(model)

表示采用零参数的 lambda(即 () )表示。您需要提供一个带有单个参数的 lambda。你可以把它写成:

model => Transform(model)

(model) => Transform(model)

当您有一个 lambda 接受多个参数时,您必须将它们放在括号内。

关于c# - 将 Action 委托(delegate)作为参数传递给构造函数时出现参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56166139/

相关文章:

c# - 如何防止 ASP.NET 3.5 SP1 覆盖我的操作?

c# - ASP.NET IAuthorizationFilter OnAuthorization

C# 在 UI 线程中等待

c# - MongoDB 连接导致 System.Net.Sockets.SocketException

ios - 为什么在 App Delegate 中调用 viewdidload 时所有 IBOutlet(s) 都为 nil?

c# - 委托(delegate) - 委托(delegate)返回类型是否也必须与其委托(delegate)的方法相匹配?

ruby - User#firstname委托(delegate)给person.firstname,但person为nil

c# - Json.NET解析对象中的数组

iOS 如何知道按下了哪个按钮 CollectionView 与自定义委托(delegate)

swift - 从 UIImagePickerController 中选择的图像未显示在 UIImageView 中