Why is it impossible to declare extension methods in a generic static class?

后端 未结 6 1496
忘了有多久
忘了有多久 2020-12-03 10:43

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

public class SimpleLinkedList where T:IComparable

6条回答
  •  旧巷少年郎
    2020-12-03 11:25

    Don't think of extension methods as being tied to the static class in which they are contained. Instead, think of them as being tied to a specific namespace. Therefore, the static class in which they are defined is simply a shell used to declare these methods within the namespace. And while you could very well write multiple classes for different types of extension methods, you shouldn't think of the class itself as anything more than a way to clearly group your extension methods.

    Extension methods do not extend any attributes of the class in which they are contained. The signature of the method will define everything about the extension method. And while you could also call your method like this, LinkedListExtensions.ToArray(...), I do not believe that was the intent for extension methods. As such, I believe the framework creators probably created the restriction you ran into as a way to inform developers simply that extension methods are self-contained and are not directly tied to the class in which they reside.

提交回复
热议问题