对具有参数化构造函数的类使用Action <t>委托

时间:2019-05-21 06:26:58

标签: c# .net lambda delegates

我有一个类Caller,该类具有一个默认构造函数和另一个用于注入依赖项的参数化构造函数。

Helper类中的某个地方,我有一个名为DoSomething的方法,该方法期望Action<T>,其中T的类型为Caller

当需要使用参数化构造函数创建Caller实例以使其注入依赖项时,如何将Caller实例作为参数传递给Action委托

注意:编写代码只是为了使问题易于理解。

public class Caller
{
    private IServiceProvider _serviceProvider;

    public string CallerName { get; set; }
    public Caller()
    {
        // Do some initializations
    }

    public Caller(IServiceProvider serviceProvider) : this()
    {
        // Service Provider is injected to get some dependencies resolved later in the code.
        _serviceProvider = serviceProvider;
    }
}

public static class Helper
{
    public static void DoSomething(Action<Caller> actOnCaller)
    {
      // Perform necessary stuff
    }
}

public class Consumer
{
    public Consumer()
    {
        // This works
        Helper.DoSomething(c => { c.CallerName = "Test"; });

        // How to pass an instance of Caller which I want with dependencies?
        IServiceProvider serviceProvider = new MyServiceProvider(); 
        var c2 = new Caller(serviceProvider);
        // This does not work because of the scope of caller variable. I tried to "new-up" the Caller instance directly in lambda but that too didnt help.
        Helper.DoSomething((c2 ) => { c2.CallerName = "Test Again"; }); 
    }
}

1 个答案:

答案 0 :(得分:1)

如果要以这种方式创建自定义的Caller实例,我不确定是否可以使用lambda表达式。但是,您可以使用返回Action<Caller>的方法:

public static Action<Caller> GetCallerAction(Caller caller)
{
  return delegate { caller.CallerName = "Test Again"; };
}

并将带有依赖项的Caller传递给该方法:

IServiceProvider serviceProvider = new MyServiceProvider(); 
var c2 = new Caller(serviceProvider);
Helper.DoSomething(GetCallerAction(c2));