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

TA貢獻1887條經驗 獲得超5個贊
你目前正在做的工作是檢查 null,但我可以幫助解決這個錯誤。如果該名稱attribute不存在,那是因為您沒有傳入或不在范圍 aTextItem中以從中獲取屬性列表。
這是另一種固定方法:
public void AddAttribute( string key, dynamic value, ref TextItem txtItem)
{
if (value != null)
{
txtItem.attributes[key] = value;
}
}
抱歉,這不是評論,沒有得到 50 個代表。
- 2 回答
- 0 關注
- 90 瀏覽
添加回答
舉報