KeyValuePair的默认值
我有一个IEnumerable<KeyValuePair<T,U>> keyValueList
types的对象,我正在使用
var getResult= keyValueList.SingleOrDefault(); if(getResult==/*default */) { } else { }
我怎样才能检查getResult
是否是默认的,以防万一我找不到正确的元素?
我无法检查它是否为null
,因为KeyValuePair
是一个结构。
尝试这个:
if (getResult.Equals(new KeyValuePair<T,U>()))
或这个:
if (getResult.Equals(default(KeyValuePair<T,U>)))
您可以创build一个通用(和通用)扩展方法,如下所示:
public static class Extensions { public static bool IsDefault<T>(this T value) where T : struct { bool isDefault = value.Equals(default(T)); return isDefault; } }
用法:
// We have to set explicit default value '0' to avoid build error: // Use of unassigned local variable 'intValue' int intValue = 0; long longValue = 12; KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11); KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>(); List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 }; KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11); KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15); Console.WriteLine(intValue.IsDefault()); // results 'True' Console.WriteLine(longValue.IsDefault()); // results 'False' Console.WriteLine(kvp1.IsDefault()); // results 'False' Console.WriteLine(kvp2.IsDefault()); // results 'True' Console.WriteLine(kvp3.IsDefault()); // results 'False' Console.WriteLine(kvp4.IsDefault()); // results 'True'
尝试这个:
KeyValuePair<string,int> current = this.recent.SingleOrDefault(r => r.Key.Equals(dialog.FileName) == true); if (current.Key == null) this.recent.Add(new KeyValuePair<string,int>(dialog.FileName,0));
if(getResult.Key == default(T) && getResult.Value == default(U))
从你原来的代码看起来像你想要的是检查列表是否为空:
var getResult= keyValueList.SingleOrDefault(); if (keyValueList.Count == 0) { /* default */ } else { }
我推荐使用扩展方法更多理解方式:
public static class KeyValuePairExtensions { public static bool IsNull<T, TU>(this KeyValuePair<T, TU> pair) { return pair.Equals(new KeyValuePair<T, TU>()); } }
然后只使用:
var countries = new Dictionary<string, string> { {"cz", "prague"}, {"de", "berlin"} }; var country = countries.FirstOrDefault(x => x.Key == "en"); if(country.IsNull()){ }
从C#7.1开始,可以使用带有types推断的default
文字来简化expression式:
var getResult= keyValueList.SingleOrDefault(); if(getResult.Equals(default)) { } else { }