我正在尝试将Action委托与传递给构造函数,但出现以下错误:
代理“动作”不带0个参数
代码:
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)
时遇到问题,因此在这里我没有遇到什么问题。
有人可以帮我弄清楚这里是什么问题吗?
答案 0 :(得分:3)
构造函数使用的Action
是Action<Variant>
,这意味着它是一段代码,它接受类型为Variant
的单个参数并返回void(因为{{1} }不返回任何内容。
当您调用构造函数时,可以向其传递一个采用单个参数的lambda,如下所示:
Action
或者您可以将接受new VariantProcessor(_myAppConnectionString, model => Transform(model));
并返回Variant
的函数的名称传递给它:
void
语法:
new VariantProcessor(_myAppConnectionString, Transform);
表示一个带零参数的lambda(即() => Transform(model)
)。您需要提供一个包含单个参数的lambda。您可以将其编写为:
()
或
model => Transform(model)
当lambda需要多个参数时,则必须将其放在方括号内。
答案 1 :(得分:1)
尝试使用以下代码。您需要在lemda中传递参数
public class AggregateCalculator : IVariantProcessor
{
private string _myAppConnectionString { get; set; }
public void Process(Variant model)
{
_myAppConnectionString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
new VariantProcessor( _myAppConnectionString,
(o) => Transform(model)
);
}
private void Transform(Variant model)
{
//logic on variant model
}
}