c# – IEnumerable,Arity和Generic Type Definitions
发布时间:2020-12-16 01:54:36 所属栏目:百科 来源:网络整理
导读:我有一个班级计数器,用钥匙计算东西.简化: public class CounterT { private DictionaryT,int counts; public void Increment(T key) { int current; bool exists = counts.TryGetValue(key,out current); if (exists) { counts[key]++; } else { counts[ke
我有一个班级计数器,用钥匙计算东西.简化:
public class Counter<T> { private Dictionary<T,int> counts; public void Increment(T key) { int current; bool exists = counts.TryGetValue(key,out current); if (exists) { counts[key]++; } else { counts[key] = 1; } } } 它还有许多其他专门针对我需求的东西,但这才是最重要的.到目前为止,它运作良好. 现在我想让它在Linq查询中使用(包含键和值).做到这一点,我想我需要实施 IEnumerable<T,int> 所以我补充说: public class Counter<T> : IEnumerable<KeyValuePair<T,int>> { // ... IEnumerator<KeyValuePair<T,int>> IEnumerable<KeyValuePair<T,int>>.GetEnumerator() { return ((IEnumerable<KeyValuePair<T,int>>)counts).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return counts.GetEnumerator(); } 遗憾的是,这会导致编译器错误
问题 >什么是arity? 更新:错字 我有一个拼写错误,同时简化我的代码发布.该代码实际上是试图实现IEnumerable< KeyValuePair< T,int>>而不是IEnumerable< T,int> 解决方法
> Arity是一种说“参数数量”的奇特方式.这是单词“二进制”(取两个参数),“一元”(取一个参数)和“三元”(取三个参数)的根.
>不,不完全:LINQ植根于函数式编程,函数编程讨厌所有状态,更喜欢没有副作用的函数.不幸的是,你的计数器保持状态:这是你修改的计数字典,这是副作用. >如果您想按键计数,LINQ已经为您提供了足够的设施. 以下是按键获取项目计数的方法: var counters = keyedData .GroupBy(item => item.MyKey) .ToDictionary(g => g.Key,g => g.Count()); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- ruby-on-rails – Cloudflare上的Heroku自定义域:重定向太
- ruby – 如何在没有catch / try / raise的情况下展开(多级返
- ruby-on-rails – 基于current_user的Rails路由范围默认值
- cocos2d-x如何截屏并保存图片
- AY2019/2020 April Semester (CFI2C11)
- 正则表达式 – 如果所有给定单词都在字符串中,则匹配正则表
- ruby-on-rails – 不确定为什么会在这里使用Proc – 而不是
- MSHFlexGrid中的数据导出为Excel
- PostgreSQL的外部表使用
- swift – 如何将NSSet转换为[String]数组?