为什么不能在声明泛型静态类扩展方法? [英] Why is it impossible to declare extension methods in a generic static class?

查看:217
本文介绍了为什么不能在声明泛型静态类扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创造了很多的扩展方法对于一些通用类,例如为

I'd like to create a lot of extension methods for some generic class, e.g. for

public class SimpleLinkedList<T> where T:IComparable

和我已经开始建立这样的方法:

And I've started creating methods like this:

public static class LinkedListExtensions
{
    public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable
    {
       //// code
    }
}

但是,当我试图让LinkedListExtensions类一般是这样的:

But when I tried to make LinkedListExtensions class generic like this:

public static class LinkedListExtensions<T> where T:IComparable
{
    public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList)
    {
         ////code
    }
}

我得到扩展方法只能在非泛型,非嵌套静态类中声明。

I get "Extension methods can only be declared in non-generic, non-nested static class".

和我试图猜出此限制是从哪里来的,没有想法。

And I'm trying to guess where this restriction came from and have no ideas.

编辑:还没有这个问题的清晰的视野。看起来这只是因某些原因实施。

Still don't have clear vision of the problem. It seems like this was just not implemented for some reason.

推荐答案

一般来说,因为您在使用扩展​​方法不指定类,编译器就没有办法知道哪个是所在班级的扩展方法定义

Generally speaking, since you do not specify the class when you use an extension method, the compiler would have no way to know which is the class where the extension method is defined:

static class GenStatic<T>
{
  static void ExtMeth(this Class c) {/*...*/}
}

Class c = new Class();
c.ExtMeth(); // Equivalent to GenStatic<T>.ExtMeth(c); what is T?

由于扩展方法本身是可以通用的,这不是真正的问题都:

Since extension methods themselves can be generic, this is no real problem at all:

static class NonGenStatic
{
  static void GenExtMeth<T>(this Class c) {/*...*/}
}

Class c = newClass();
c.ExtMeth<Class2>(); // Equivalent to NonGenStatic.ExtMeth<Class2>(c); OK

您可以轻松地重写你的榜样,使静态类是不通用的,但一般的方法。其实,这是.NET类,如可枚举如何写的。

You can easily rewrite your example so that the static class is not generic, but the generic methods are. In fact, this is how .NET classes such as Enumerable are written.

  public static class LinkedListExtensions
  {
    public static T[] ToArray<T>(this SimpleLinkedList<T> where T:IComparable simpleLinkedList)
    {
      // code
    }
  }

这篇关于为什么不能在声明泛型静态类扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆