【问题标题】:AddIfNotNull Dictionary<string, dynamic> methodAddIfNotNull Dictionary<string, dynamic> 方法
【发布时间】:2019-09-14 14:42:18
【问题描述】:

我有多个创建强类型对象的方法。当我将属性映射到此对象时,我手动将键值对添加到字典中,但是正在处理的 JSON 中的某些属性可能不包含值,下次调用它可能包含值。

如何处理不添加到列表中的包含 null 的键?请注意,我将有许多其他对象类型。下面只是一个例子

public TextType GetTextType(JToken token)
        {
            TextType text = new TextType()
            {
                type = "text",
                //Dictionary<string, dynamic>
                attributes = {
                    ["font-family"] = component.style.fontFamily, //NULL
                    ["font-size"] = component.style.fontSize, //12
                    ["font-style"] = component.style.fontStyle //Bold
                }
            };
            return text;
        }

对象:

public class TextItem
{
    public string type { get; set; }
    public IDictionary<string, dynamic> attributes { get; set; }

    public TextItem()
    {
        attributes = new Dictionary<string, dynamic>();

    }
}

我有这个方法,它会抛出“名称attributes 在当前上下文中不存在”

public void AddAttribute( string key, dynamic value)
{
    if (value != null)
    {
        attributes[key] = value;
    }
}

如何修改这个方法,以便我可以在多个方法中调用它,并且只有在它包含值时才添加键。因为我不想为所有键值对编写多个 if 语句。

【问题讨论】:

  • 也许你想创建扩展方法? AddIfNotNull
  • 问题标题甚至与您描述的问题不匹配。您正在谈论一个编译器错误,但寻求有关 null 处理的建议。
  • @Johnny 你有这方面的例子吗?只是不确定如何从我的实现中引用所有内容
  • @CSharpie 抱歉,我已经更新了标题。
  • @Mask-dCodex 我发布了答案。

标签: c# json dictionary json.net


【解决方案1】:

您当前正在执行的操作可用于检查 null,但我可以帮助解决错误。如果名称 attribute 不存在,那是因为您没有传入或在范围内没有 TextItem 来获取属性列表。

这是另一种固定方法:

public void AddAttribute( string key, dynamic value,  ref TextItem txtItem)
{
    if (value != null)
    {
        txtItem.attributes[key] = value;
    }
}

很抱歉,这不是评论,没有得到 50 个代表。

【讨论】:

  • 谢谢拉里,我知道我有多种项目类型,这意味着它只会处理 TextItem 但我还有 5 多个对象来检查密钥对不确定传递给此方法以允许的内容不同的对象类型。
  • 为什么是ref TextItem txtItem
【解决方案2】:

可能为IDictionary&lt;TKey, TValue&gt;添加扩展方法,例如

public static class DictionaryExtension
{
    public static void AddIfNotNull<TKey, TValue>(
        this IDictionary<TKey, TValue> dict, TKey key, TValue value)
        where TValue : class 
    {
        if (value != null)
        {
            dict[key] = value;
        }
    }
}

textItem.attributes.AddIfNotNull(1, null); //won't be added
textItem.attributes.AddIfNotNull(1, "a"); //will be added

【讨论】:

  • 谢谢这应该工作我太忙于尝试将它实现到同​​一个类中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 2012-09-21
相关资源
最近更新 更多