在 C# 中扩展 Enumerable 类?
我有情况扩展 C# 中的 Enumerable 类以添加接受长参数的新 Range 方法。我无法定义这样的方法,
public static IEnumerable<long> Range(this Enumerable source, long start, long length)
{
for (long i = start; i < length; i++)
{
yield return i;
}
}
因为扩展方法只能通过其对象访问。它给了我一个错误
'System.Linq.Enumerable':静态类型 不能用作参数
有人可以澄清一下如何执行此
操作 注意:我知道我们可以在没有扩展方法的情况下轻松解决此问题,但我需要这个 Enumrable 类。
I have situation to extend the Enumerable class in c# to add the new Range method that accepts long parameters. I cannot define the method like this
public static IEnumerable<long> Range(this Enumerable source, long start, long length)
{
for (long i = start; i < length; i++)
{
yield return i;
}
}
Since extension methods are accesible only through its objects. And it gives me an error
'System.Linq.Enumerable': static types
cannot be used as parameters
Can someonce clarify me how to do this
Note: I know we can easily solve this without extension methods, but i needed this Enumrable class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您(像我一样)正在寻找静态扩展方法:
http://madprops.org/blog/ static-extension-methods/
这在 C# 中是不可能的。最接近的替代方法是定义另一个具有相似名称的静态类(LongEnumerable?)并向其中添加静态方法。
You (like me) are looking for static extension methods:
http://madprops.org/blog/static-extension-methods/
It's not possible in C#. The closest alternative is to define another static class with a similar name (LongEnumerable?) and add your static method to that.
扩展方法只能在类型的实例上调用,并且由于
Enumerable
是静态类型,因此永远不会有任何它的实例,这意味着您无法扩展它。将
Range
方法作为IEnumerable
的扩展也是没有意义的。您的方法只是生成一系列long
值,不需要扩展任何特定实例。使用标准静态实用程序方法代替:
Extension methods can only be called on instances of a type, and since
Enumerable
is a static type there will never be any instances of it, which means that you can't extend it.It makes no sense to have your
Range
method as an extension onIEnumerable<T>
either. Your method just generates a sequence oflong
values, it doesn't need to extend any particular instance.Use a standard static utility method instead:
为什么要扩展 System.Linq.Enumerable?
此类使用扩展方法来扩展实现 IEnumerable 的其他类型。
结果将是,您会调用:
您宁愿直接扩展长类:
这样您可以从
Why do you want to extend System.Linq.Enumerable?
This class uses Extension methods to extend OTHER types that implement IEnumerable.
The result would be, that you'd call:
You'd rather extend the long class directly:
This way you can start with
您无法扩展
Enumerable
类,因为您没有Enumerable
实例 - 它是一个static
类。扩展方法仅适用于实例,它们永远不会适用于静态类本身。You can't extend the
Enumerable
class, since you don't have anEnumerable
instance - it's astatic
class. Extension methods only work on instances, they never work on the static class itself.您必须为此创建自己的实用程序类;您可以通过扩展方法添加静态方法。
You're going to have to create your own utility class for that; you can'd add static methods via extension methods.