C# Extension Methods Architecture Question

I recently asked this question: Compiler error referencing custom C# extension method

Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...

If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?

I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...

My question is: Why can't we create an extension method that will work as a static Method?


I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - ie

var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();

which enables LINQ:

var foo = (from x in data
           where x.IsActive
           order by x.Price
           select x).First();

With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.

As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.


Because that feature doesn't exist in C#.

As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.

For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.

The community is asking if we think it's a good idea for C# 4.0


My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.

The this parameter allows control and thus doesn't break compatibility.

Just an idea though.

链接地址: http://www.djcxy.com/p/96954.html

上一篇: 在可以修改的类上使用扩展方法是可以接受的

下一篇: C#扩展方法体系结构问题