为什么不能在泛型静态类中声明扩展方法?

编程入门 行业动态 更新时间:2024-10-26 18:17:24
本文介绍了为什么不能在泛型静态类中声明扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 } }

更多推荐

为什么不能在泛型静态类中声明扩展方法?

本文发布于:2023-11-09 10:32:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能在   静态   类中   声明   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!