c# – 如何告诉DataContract使用基类的GetEnumerator?
发布时间:2020-12-15 21:31:56 所属栏目:百科 来源:网络整理
导读:我有一个实现Dictionary的泛型类.我创建了一个自定义的GetEnumerator,它循环遍历值而不是KeyValuePairs,因为我通常不关心键.这是一个快速示例: public class AssetHolderT : Dictionarystring,T,IEnumerable,INotifyCollectionChanged,INotifyPropertyChang
我有一个实现Dictionary的泛型类.我创建了一个自定义的GetEnumerator,它循环遍历值而不是KeyValuePairs,因为我通常不关心键.这是一个快速示例:
public class AssetHolder<T> : Dictionary<string,T>,IEnumerable,INotifyCollectionChanged,INotifyPropertyChanged where T : Asset { // methods that don't relate to this post ... // enumeration methods IEnumerator System.Collections.IEnumerable.GetEnumerator() // this one is called by WPF objects like DataGrids { return base.Values.GetEnumerator(); } new public IEnumerator<T> GetEnumerator() // this enumerator is called by the foreach command in c# code { return base.Values.GetEnumerator(); } } 我没有向我的类添加任何数据(我只添加了方法),所以为了使其可序列化,我将[DataContract]添加到类的顶部而没有任何[DataMember]标记.我认为这只会使用基类的数据进行序列化/反序列化,但是我收到以下错误: 无法将类型为’Enumerator [System.String,SignalEngineeringTestPlanner.Asset]’的对象强制转换为’System.Collections.Generic.IEnumerator`1 [System.Collections.Generic.KeyValuePair`2 我认为这意味着DataContractSerializer正在调用孩子的枚举器并且它变得混乱,因为它期望一对,但它正在获得一个Asset对象.有没有办法可以(1)告诉DataContractSerializer使用基类的枚举器,或者(2)创建一个特殊的枚举函数并告诉DataContractSerializer只使用那个? 解决方法
您可以在类中将类型标记为Dictionary,而不是派生类.缺点是您在使用它时必须使用它(或使用正确的类型单独引用).
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |