将 Lambda 表达式传递给方法 C#

Passing Lambda expression to a method C#

能否建议我如何实施“Alexa”class?

var alexa = new Alexa();
        Console.WriteLine(alexa.Talk()); //print hello, i am Alexa
        alexa.Configure(x =>
        {
            x.GreetingMessage = "Hello { OwnerName}, I am at your service";
            x.OwnerName = "Bob Marley";
        });
        Console.WriteLine(alexa.Talk()); //print Hello Bob Marley, I am at your service

我尝试将方法实现为:

public void Configure(Action<Configration> p)
    {
        
    }

public class Configration
{
    public string GreetingMessage { get; set; }
    public string OwnerName { get; set; }
}

但我不知道如何打印 GreetingMessage。

谢谢

你可以这样做:

public class Alexa
{
    private Configration _configration;

    public Alexa()
    {
        _configration = new Configration
        {
            // This sets the default message you wanted.
            GreetingMessage = "Hello, I am Alexa."
        };
    }

    public void Configure(Action<Configration> configuration)
    {
        // I'll explain this below.
        configuration(_configration);
    }

    public string Talk()
    {
        return _configration.GreetingMessage;
    }
}

但是,您确实需要更改调用它的方式以获得您想要的结果。当您这样做时:

alexa.Configure(x =>
{
    x.GreetingMessage = $"Hello {x.OwnerName}, I am at your service";
    x.OwnerName = "Bob Marley";
});

它实际上会打印 Hello , I am at your service 而不是预期的 Hello Bob Marley, I am at your service。这是因为 OwnerName 尚未设置为 Bob Marley。要解决这个问题,我们需要将分配更改为 OwnerName,以便在问候语中使用它之前出现,如下所示:

alexa.Configure(x =>
{
    x.OwnerName = "Bob Marley";
    x.GreetingMessage = $"Hello {x.OwnerName}, I am at your service";
});

最后,您可能想知道 configuration(_configration); 在做什么。它实际上是 configuration.Invoke(_configration); 的 short-hand,它将执行 Action 委托,将 _configration 作为 Configuration 参数传递。

使用以下方式调用它:

static void Main(string[] args)
{
    var alexa = new Alexa();
    Console.WriteLine(alexa.Talk());
    alexa.Configure(x =>
    {
        x.OwnerName = "Bob Marley";
        x.GreetingMessage = $"Hello {x.OwnerName}, I am at your service";
    });
    Console.WriteLine(alexa.Talk());
}

结果:

Hello, I am Alexa.
Hello Bob Marley, I am at your service

如果您有权访问 talk 方法,只需将配置传递给操作即可。然后从传递给操作的 class 中获取信息。

public class Configration
{
    public string GreetingMessage { get; set; }
    public string OwnerName { get; set; }
}

public class Alexa()
{
    public Configration ConfigurationModel { get; set; }
    public Action<Configration> Configration { get; set; }

    public void Talk()
    {
        this.Configuration.Invoke(ConfigurationModel);
        Console.WriteLine(ConfigurationModel.GreetingMessage);
    }
}

void main()
{
    var alexa = new Alexa();
    Console.WriteLine(alexa.Talk()); //print hello, i am Alexa
    alexa.Configure(x =>
    {
        x.GreetingMessage = "Hello { OwnerName}, I am at your service";
        x.OwnerName = "Bob Marley";
    });
    Console.WriteLine(alexa.Talk()); //print Hello Bob Marley, I am at your service
}