C# 在可序列化字典上使用foreach语句
我有一个为WCF REST web服务创建的可序列化字典C# 在可序列化字典上使用foreach语句,c#,wcf,dictionary,ienumerable,C#,Wcf,Dictionary,Ienumerable,我有一个为WCF REST web服务创建的可序列化字典 [Serializable] public class jsonDictionary<TKey, TValue> : ISerializable { private Dictionary<TKey, TValue> _Dictionary; public jsonDictionary() { _Dictionary = new Dictionary<TKey, TVal
[Serializable]
public class jsonDictionary<TKey, TValue> : ISerializable
{
private Dictionary<TKey, TValue> _Dictionary;
public jsonDictionary()
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public jsonDictionary(SerializationInfo info, StreamingContext context)
{
_Dictionary = new Dictionary<TKey, TValue>();
}
public TValue this[TKey key]
{
get { return _Dictionary[key]; }
set { _Dictionary[key] = value; }
}
public void Add(TKey key, TValue value)
{
_Dictionary.Add(key, value);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (TKey key in _Dictionary.Keys)
info.AddValue(key.ToString(), _Dictionary[key]);
}
}
然而,我不断得到错误:
foreach statement cannot operate on variables of type 'ZTERest.jsonDictionary<string,string>' because 'ZTERest.jsonDictionary<string,string>' does not contain a public definition for 'GetEnumerator'
foreach语句无法对“ZTERest.jsonDictionary”类型的变量进行操作,因为“ZTERest.jsonDictionary”不包含“GetEnumerator”的公共定义
我知道我必须对IEnumerable或IEnumerator接口做些什么,但我不确定如何做。您的类需要实现IEnumerable才能对字典的键执行foreach,因此您的类将如下所示
public class jsonDictionary<TKey, TValue> : ISerializable, IEnumerable<TKey>
字典提供键/值查找是有原因的,它不是您通常要迭代的东西。您的类正在包装的泛型
Dictionary
对象已经有了一个名为ContainsKey()
的方法,该方法将完全满足您的要求,而无需检查每个键/值对以查看它是否存在。不需要公开迭代器,只需将其添加到类中即可
public bool ContainsKey(TKey key)
{
return _Dictionary.ContainsKey(key);
}
这样称呼它
if (dictionary.ContainsKey("Something"))
{
//do something
}
如果您确实需要遍历字典(而不仅仅是检查某个键是否存在),dictionary.Keys属性将返回一个可枚举集合,您可以使用该集合遍历字典:
foreach(var key in dictionary.Keys)
{
if(dictionary[key] == "something")
{
// Do something
}
}
这很好,谢谢,并回答了我的问题。我选择了另一个答案,因为它的效率更高。欢迎光临。这很好,但只是因为您想在自定义dic对象上使用foreach,才发布了此消息。:)
public bool ContainsKey(TKey key)
{
return _Dictionary.ContainsKey(key);
}
if (dictionary.ContainsKey("Something"))
{
//do something
}
foreach(var key in dictionary.Keys)
{
if(dictionary[key] == "something")
{
// Do something
}
}