【问题标题】:List<Dictionary> foreach get valueList<Dictionary> foreach 获取值
【发布时间】:2019-06-25 13:35:45
【问题描述】:
List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
Dictionary<string, Object> objs = new Dictionary<string, object>();
for (int i = 1; i <= onlineolanlar.Count; i++)
{
    objs.Add(i.ToString(), new userLevel() { UserID = userID.ToString(), Presence = UserLevelBul.ToString() });
}
foreach (var item5 in objs.Values)
{
    //How can I access item5 properties here??
}

大家好,

我怎样才能达到那个 foreach 循环的值?

item5 应该有属性 useriduserlevelbul 但我无法访问它们。

【问题讨论】:

  • 尽可能详细地解释这一点:in item5 there are userid and userlevelbul but i cant reach them
  • 使用UserID, Presence, etc.. 创建一个类型并将该类型添加到objs,而不是添加匿名类型。
  • 当我写 item5.它只显示 equals.gethashcode 等。没有用户 ID...
  • 声明你的字典objsDictionary&lt;string, userLevel&gt;
  • 很少有合法地需要直接使用Object 类型的情况。 99% 的情况下,您希望使用更具体的类型 (userLevel)。

标签: c# asp.net dictionary


【解决方案1】:

您将字典 objs 声明为 Dictionary&lt;string, object&gt;。但实际上您只想添加(以及以后使用)userLevel 类型的条目。

所以只需用正确的类型声明字典:

Dictionary<string, userLevel> objs = new Dictionary<string, userLevel>();

那么你就可以直接使用了:

foreach (var item5 in objs.Values)
{
     Console.WriteLine(item5.userID)
     Console.WriteLine(item5.Presence)
}

因为现在objs.Valuesitem5 中的元素属于userLevel 类型。

【讨论】:

    【解决方案2】:

    userLevelDictionary&lt;string, Object&gt; 一起使用而不是Object 或使用Explicit casting(如果您由于某种原因无法更改object):

    foreach (var item5 in objs.Values)
    {
         string userId = ((userLevel)item5).UserID;
         // or
         // string userId = (item5 as userLevel).UserID;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多