Csharp/C#教程:IEnumerable ,Arity和Generic Type Definitions分享


IEnumerable ,Arity和Generic Type Definitions

我有一个class级计数器 ,用钥匙计算东西。 简化:

public class Counter { private Dictionary 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 

所以我补充说:

 public class Counter : IEnumerable<KeyValuePair> { // ... IEnumerator<KeyValuePair> IEnumerable<KeyValuePair>.GetEnumerator() { return ((IEnumerable<KeyValuePair>)counts).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return counts.GetEnumerator(); } 

遗憾的是,这会导致编译器错误

提供的generics参数的数量不等于generics类型定义的arity。 参数名称:instantiation

问题

  1. 什么是arity?
  2. 我是否正确地从Linq使用此类型?
  3. 我该如何修复实施?

更新 :错字

我有一个错字,同时简化我的代码发布。 代码实际上是在尝试实现IEnumerable<KeyValuePair>而不是IEnumerable

  1. Arity是一种说“参数数量”的奇特方式。 这是单词“二进制”(取两个参数),“一元”(取一个参数)和“三元”(取三个参数)的根。
  2. 不,不完全:LINQ植根于函数式编程,函数编程讨厌所有状态,更喜欢没有副作用的函数。 不幸的是,你的计数器保持状态:这是你修改的counts字典,这是副作用。
  3. 如果您想按键计算内容,LINQ已经为您提供了足够的设施。

以下是按键获取项目计数的方法:

上述就是C#学习教程:IEnumerable ,Arity和Generic Type Definitions分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 var counters = keyedData .GroupBy(item => item.MyKey) .ToDictionary(g => g.Key, g => g.Count()); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/956554.html

(0)
上一篇 2021年11月20日
下一篇 2021年11月20日

精彩推荐