亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

AddIfNotNull Dictionary<string, dynamic> 方法

AddIfNotNull Dictionary<string, dynamic> 方法

C#
慕俠2389804 2022-12-31 10:28:15
我有多種創建強類型對象的方法。當我將屬性映射到該對象時,我手動將鍵值對添加到字典中,但是正在處理的 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 語句。
查看完整描述

2 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

也許添加擴展方法IDictionary<TKey, TValue>,例如


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


查看完整回答
反對 回復 2022-12-31
?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

你目前正在做的工作是檢查 null,但我可以幫助解決這個錯誤。如果該名稱attribute不存在,那是因為您沒有傳入或不在范圍 aTextItem中以從中獲取屬性列表。


這是另一種固定方法:


public void AddAttribute( string key, dynamic value,  ref TextItem txtItem)

{

    if (value != null)

    {

        txtItem.attributes[key] = value;

    }

}

抱歉,這不是評論,沒有得到 50 個代表。


查看完整回答
反對 回復 2022-12-31
  • 2 回答
  • 0 關注
  • 90 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號