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

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

问题描述

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

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

您可以轻松地重写您的示例,以便静态类不是通用的,但通用方法是通用的.其实Enumerable等.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天全站免登陆