【发布时间】: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