【问题标题】:output value types from If Else block using Dictionaries使用字典从 If Else 块输出值类型
【发布时间】:2022-01-18 22:24:15
【问题描述】:

我正在尝试将值添加到外部变量 val_dict 从 if 和 else 循环中的块。问题是 if 块的输出类型与 else 块的输出类型不同,如果我将变量初始化为输出类型类之一,则会为它们中的任何一个抛出类型错误。

简而言之,val_dict 是一个可以是字典null object 的对象,但我似乎无法为这两种对象类型定义一个通用类型。

代码如下:

Dictionary<string, Dictionary<string,object>> data_dict =
             new Dictionary<string, Dictionary<string, object>>();

foreach (KeyValuePair<(string, string), object> cat_nam_val in dataset) 
{
    var val_dict = new Dictionary<string, object>(); //use val_dict as dictionary or object
    
    if (target_survey_id != null)
    {
        data_dict[target_survey_id].TryGetValue(cat_nam_val.Key.Item1, out val_dict);
    }
    else
    { 
       data_dict.TryGetValue(cat_nam_val.Key.Item1, out val_dict);
    }

    if (IsDictionary(val_dict)); 
    {
        val_dict[cat_nam_val.Key.Item2]  = cat_nam_val.Value; //generate new dict becoz val_dict is an object so cannot be indexed
    }
} 

【问题讨论】:

  • 我已经清理了您注释掉的代码和多余的空格。也就是说,仍然不清楚您要做什么。没有迹象表明data_dict 是什么,它来自哪里,或者它应该如何工作。此外,使用字典作为输出参数很可能没有意义。
  • 谢谢我也添加了data_dict 的初始化,问题是val_dict 可能是字典null object,具体取决于数据。我需要创建一个包含这两种对象类型的类。我试图绕过它但失败了。

标签: c# .net dictionary


【解决方案1】:

使用out 时不能强制类型。因此,您可以使用一个临时的 out 变量,然后在您确定它是字典的情况下对其进行转换。

foreach (KeyValuePair<(string, string), object> cat_nam_val in dataset)
{
    var val_dict = new Dictionary<string, object>(); //use val_dict as dictionary or object

    if (target_survey_id != null)
    {
        // use a temporary variable to work around type mismatch
        data_dict[target_survey_id].TryGetValue(cat_nam_val.Key.Item1, out var temp_val_dict);
        
        // if you know that object is a dictionary, cast and assign
        val_dict = (Dictionary<string, object>)temp_val_dict;
    }
    else
    {
        data_dict.TryGetValue(cat_nam_val.Key.Item1, out val_dict);
    }

    if (IsDictionary(val_dict))
    {
        val_dict[cat_nam_val.Key.Item2] = cat_nam_val.Value; //generate new dict becoz val_dict is an object so cannot be indexed
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2015-03-21
    相关资源
    最近更新 更多