簡體   English   中英

C#使用Lambda表達式將參數傳遞給方法

[英]C# Pass parameter to method using lambda expression

使用ASP.Net的任何人都可能會看到接受Action<T>委托的方法,該委托用於配置某些選項。 以ASP.Net Core MVC Startup.cs為例。

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication().AddJwtBearer(options => {
        options.Audience = "something";
        // ...
    });

    //...
}

.AddJwtBearer()方法在lambda表達式中獲取一個帶有配置參數Action<T>委托我試圖做的就是在我的一個項目中復制它,但是沒有運氣。 我把Method(Action<T> action)部分記下來了,但是我似乎無法檢索調用該方法時配置的結果對象。

一些上下文代碼:

構建器類方法:

public ReporterBuilder SetEmail(Action<EmailConfig> config)
{
    if (config is null)
        throw new ArgumentNullException();

    // Get configured EmailConfig somehow...

    return this;
}

EmailConfig模型:

public class EmailConfig
{
    public EmailProvider EmailProvider { get; set; }
    public string Host { get; set; }
    public int Port { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FromAddress { get; set; }
    public string ToAddress { get; set; }
}

所以我想在這里實現的是:

Reporter reporter = new ReporterBuilder()
    .SetEmail(config => {
        config.EmailProvider = EmailProvider.Other;
        config.Host = "something";
        // ...
    })
    .Build();

我查看了GitHub上的一些Microsoft存儲庫(aspnet / DependencyInjection,aspnet / Options是在IoC容器中使用此方法的兩個主要存儲庫),以了解它們如何從Action<T>委托中獲取值,並且絕對沒運氣。

在互聯網上進行幾個小時的搜索也無濟於事,因為大多數文章已經過時或與我正在嘗試的工作無關。

非常歡迎您提供有關如何進行此工作的幫助,也歡迎提出關於可以更好地完成此工作的建議。

您的方法需要實例化該對象,然后調用該方法,將該對象傳遞給該方法。 Func<T>將返回一個對象。 這是ActionT<T> ,不返回任何內容。 而是接受對象。

public ReporterBuilder SetEmail(Action<EmailConfig> config)
{
    if (config == null)
        throw new ArgumentNullException();

    var cfg = new EmailConfig();

    // optionally populate the cfg with 
    // default configuration before calling method

    config(cfg);

    // cfg contains your configuration 
    // and is full of that thing called 'love'

    return this;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM