[英]Extension methods not showing even on implementing IEnumerable
This is my code: 这是我的代码:
class myClass : IEnumerable
{
public Dictionary<int, string> dctIdName = new Dictionary<int, string>();
public myClass()
{
for (int idx = 0; idx < 100; idx++)
{
dctIdName.Add(idx, string.Format("Item{0}", idx));
}
}
// IEnumerable Member
public IEnumerator GetEnumerator()
{
foreach (object o in dctIdName)
{
yield return o;
}
}
}
Where i create an object of this class and use it in this manner i do not get the LINQ extension methods like Where
, Count
, etc. 我在哪里创建此类的对象并以这种方式使用它,我没有得到诸如
Where
, Count
等的LINQ扩展方法。
myClass obj = new myClass();
var d = obj.Where( x => x.Key == 10); //<-- Error here
The namespaces i have included are: 我包括的名称空间是:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
How to fix this? 如何解决这个问题?
It does work. 确实有效。
AsParallel
is an extension method on IEnumerable
. AsParallel
是IEnumerable
的扩展方法。 Most extension methods though work on IEnumerable<T>
. 尽管大多数扩展方法都可以在
IEnumerable<T>
。 Your class should start with this: 您的课程应从以下内容开始:
class myClass : IEnumerable<SomeType>
Or: 要么:
class myClass<T> : IEnumerable<T>
(Where T
is the type of the generic type argument) (其中
T
是泛型类型参数的类型)
class myClass : IEnumerable<KeyValuePair<int, string>>
{
public Dictionary<int, string> dctIdName = new Dictionary<int, string>();
public myClass()
{
for (int idx = 0; idx < 100; idx++)
{
dctIdName.Add(idx, string.Format("Item{0}", idx));
}
}
// IEnumerable Member
public IEnumerator<KeyValuePair<int, string>> GetEnumerator()
{
foreach (KeyValuePair<int, string> o in dctIdName)
{
yield return o;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
You need to implement the generic version of IEnumerable. 您需要实现IEnumerable的通用版本。 I guess in your case it would be:
我想在您的情况下将是:
IEnumerable<KeyValuePair<int, string>>
or 要么
IEnumerable<object>
Only the following extension methods are defined by the .NET Framework for IEnumerable
.NET Framework for
IEnumerable
仅定义以下扩展方法
AsParallel() - Enables parallelization of a query.(Defined by ParallelEnumerable.)
AsParallel()-启用查询的并行化。(由ParallelEnumerable定义。)
AsQueryable() - Converts an IEnumerable to an IQueryable.(Defined by Queryable.)
AsQueryable()-将IEnumerable转换为IQueryable。(由Queryable定义。)
Cast() - Casts the elements of an IEnumerable to the specified type.(Defined by Enumerable.)
Cast()-将IEnumerable的元素强制转换为指定的类型。(由Enumerable定义。)
OfType() - Filters the elements of an IEnumerable based on a specified type.(Defined by Enumerable.)
OfType()-根据指定的类型过滤IEnumerable的元素。(由Enumerable定义。)
IEnumerable<T>
is what you are looking for. IEnumerable<T>
是您要寻找的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.