[英]Dictionary with Enum value type - calling the indexer for a key not in the dictionary?
我遇到一個小問題。 我有
IDictionary<Something,MyEnum> map;
我想寫一個方法:
MyEnum GetMapping(Something x);
使用有點像:
MyEnum e = GetMapping(x)
if(e!=null){...}
但是當然,問題在於,由於MyEnum
是基於int
的標准Enum
,因此GetMapping
無法返回null。 必須添加一個單獨的DoesMappingExist
方法似乎很麻煩,是否有一種巧妙的方法可以解決此問題?
而且, map[AnObjectNotInTheMap]
實際返回的內容是什么-只是Default(MyEnum)
即0
?
只需使用可為空的枚舉即可:
IDictionary<Something,MyEnum?> map;
您的方法也將更改為:
MyEnum? GetMapping(Something x);
您可以使用Nullable<T>
將值類型用作nullable,這是T?
的簡寫T?
。
因此,您的代碼應如下所示:
MyEnum? GetMapping(Something x)
{
if (...) return MyEnum.SomeValue;
if (...) return MyEnum.OtherValue;
return null;
}
然后,像這樣使用它:
MyEnum? e = GetMapping(x);
if(e.HasValue)
{
var mapped = e.Value;
...
}
Enum的默認值為0。因此,您沒有將0分配給MyEnum的任何成員,0表示沒有映射。 除非必須在MyEnum中分配0,否則這應該是最簡單的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.