如何在 C# 中使用 foreach 循环向声明数组添加新声明?

How to add new claims to claim array using foreach loop in C#?

我想在 foreach 循环中向声明数组添加新声明。怎么做?

        //userRoles is a list of string contains roles. 
        var userRoles = _repository.GetRolesOfUser(username); 
        var claim = new[]
        {
            new Claim("username", username)
                                                 
        };
        //I want to add new claims to claim like below. 
        //When I put Add I am getting error like this
        // "Claim[] doesn't contain definition for Add." 
        foreach(var userRole in userRoles)
        {
            claim.Add(new Claim("roles", userRole)); 
        }

我最后想要的是这样的,其中 Role_1、Role_2 等来自 userRole 列表。

var claim = new[]
            {
                new Claim("username", username)                    
                new Claim("roles", "Role_1")
                new Claim("roles", "Role_2")
                new Claim("roles", "Role_3")
                new Claim("roles", "Role_4")
             }

正如约翰所说,C# 中的数组不包含 add 方法。它只包含附加方法。

如果要向数组中添加新元素,应该使用 append 而不是 add。

更多细节,您可以参考下面的测试演示代码:

        var claims = new[]{
        new Claim("username", "aaa")

    };
        claims.Append(new Claim("aaa","aaa"));

你的代码应该是这样的:

    //userRoles is a list of string contains roles. 
    var userRoles = _repository.GetRolesOfUser(username); 
    var claim = new[]
    {
        new Claim("username", username)
                                             
    };
    //I want to add new claims to claim like below. 
    //When I put Add I am getting error like this
    // "Claim[] doesn't contain definition for Add." 
    foreach(var userRole in userRoles)
    {
        claim .Append(new Claim("roles", userRole));
    }

或者您可以使用 List<Claim> 而不是 var claims = new[],如下所示:

        var claim = new List<Claim>();

        claim.Add("username", "aaa");
        claim.Add("username", "bbbb");