4

我正在尝试从哈希表中检索布尔值...我的代码如下所示:

Hashtable h = new Hastable();

...

h["foo"] = true;

...

object o = h["foo"];
if( o == null ) { return false; }
if( o.GetType() != typeof(bool) ) { return false; }
return (bool)o;

相反,我对对象使用这样的东西

return h["foo"] as MyObject;

布尔值有更好的解决方案吗?

4

5 回答 5

6

好吧,如果必须使用Hashtable (或由于object其他原因键入数据),请考虑:

object obj = true;
bool b = (obj as bool?) ?? false;
// b -> true

和:

object obj = "hello";
bool b = (obj as bool?) ?? false;
// b -> false

也就是说,bool?(or Nullable<bool>) 很高兴成为as目标(因为null它是可空类型的有效值),并且结果很容易(与??)合并为bool

快乐编码。

于 2012-05-28T06:02:59.710 回答
2

您可以使用扩展方法来帮助使工作更容易忍受:

public static class IDictionaryExtensions
{
    public static T? GetValue<T>(this IDictionary dictionary, object key) 
                  where T : struct
    {
        if (!dictionary.Contains(key))
            return null;
        object o = dictionary[key];
        if (o == null)
            return null;
        if (!(o is T))
            return null;
        return (T) o;
    }

    public static T GetValue<T>(this IDictionary dictionary, object key,
                                T defaultValue) where T : struct
    {
        return dictionary.GetValue<T>(key) ?? defaultValue;
    }
}

用于:

return h.GetValue("foo", false);

您可以轻松地调整它以在正确的位置引发异常,或记录缺失值或类型不匹配。

于 2012-05-28T06:09:47.687 回答
2

不要使用哈希表。自从 .NET 2.0 出现以来,这些已经过时了七年。请改用通用集合,例如 a Dictionary

Dictionary<string, bool> myDict = new Dictionary<string, bool>();
myDict["foo"] = true;

bool myBool = myDict["foo"];

泛型非常棒。帮自己一个忙,花几个小时研究它们。你可以从MSDN开始,我真的很喜欢 Jon Skeet 的书,C# in Depth,它涵盖了这个主题……深入。

于 2012-05-28T05:40:55.290 回答
1

您应该使用泛型

Dictionary<string, bool> 

而不是(过时的)哈希表。

于 2012-05-28T05:45:29.180 回答
0
bool bVal = false;
object oVal;
if (hash.TryGetValue("foo", out oVal)) {
    bVal = (bool) oVal;
}
于 2016-12-19T02:13:00.927 回答