C# - 在流畅的界面中添加列表中的值

C# - Add values from list in a fluent interface

我是以下代码:

var token = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(_Signature)
    .AddClaim("test", 3)
    .Build();

我想添加多个值(这里称为'claims'):

    .AddClaim("test", 3)
    .AddClaim("test2", 4)
    .AddClaim("test3", 5)

如果我有字典:

    Dictionary<string, int> myDictionary;

如何编写表达式以便添加字典中的所有值? (伪代码:AddClaim(myDictionary))。

编辑: 我正在寻找适合 'fluent' 流程而非外部循环的方法。

我不确定您是否可以在此处使用循环:

var tokenBuilder = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(_Signature);

for (KeyValuePair<string, int> entry in myDictionary) {
    tokenBuilder.AddClaim(entry.Key, entry.Value);
}

var token = tokenBuilder.build();

可以使用for循环

for (KeyValuePair<string, int> claimval in myDictionary) {
    tokenBuilder.AddClaim(claimval.Key, claimval.Value);
}

你问的不是很清楚。如果您想要您正在使用的 API 中的方法,那么这取决于 API 的实现者。例如。也许你在这里使用 Jwt.Net,如果你想要那个功能,你必须添加类似的东西 "out-of-the-box"。

不然你自己写循环就出不来了。但是,您可以做的是将循环封装在扩展方法中:

static class JwtExtensions
{
    public static JwtBuilder AddClaims<TKey, TValue>(this JwtBuilder builder, Dictionary<TKey, TValue> dictionary)
    {
        foreach (var kvp in dictionary)
        {
            builder.AddClaim(kvp.Key, kvp.Value);
        }

        return builder;
    }
}

那你可以这样写:

var token = new JwtBuilder()
    .WithAlgorithm(new HMACSHA256Algorithm())
    .WithSecret(_Signature)
    .AddClaims(myDictionary)
    .Build();

如果我理解你,你正在寻求扩展 JwtBuilder class

的流畅界面

我敏锐的直觉告诉我,没有接口通过 WithAlgorithm 等其他方法传递,很可能只是“JwtBuilder” class 本身

在这种情况下,您可以轻松实现 extension method 来实现您最疯狂的梦想

public static class JwtBuilder Extensions
{
    public static JwtBuilder AddClaims(this JwtBuilder source, Dictionary<string, int> claims)
    {
        for (KeyValuePair<string, int> claim in claims) 
        {
            source.AddClaim(claim .Key, claim .Value);
        }

        return source;
    }
}

Note : you hould check the return type of the other methods as it might be an interface, in that case just use it in your extension me your extension method

看起来像这样

public static IInterface AddClaims(this <IInterface> source, Dictionary<string, int> claims)

// Or  

public static T AddClaims<T>(this T source, Dictionary<string, int> claims)
where T : ISomeInterface