0

我想在 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")
             }
4

1 回答 1

1

正如 John 所说,C# 中的数组不包含 add 方法。它只包含 append 方法。

如果要将新元素添加到数组中,则应使用 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");
于 2021-02-01T07:00:38.080 回答