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

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

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

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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