C#扩展方法体系问题

C#扩展方法体系问题

本文介绍了C#扩展方法体系问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我问这个问题:

I recently asked this question:http://stackoverflow.com/questions/638463

马克Gravell的答案是完美的,它解决了我的问题。但它给了我一些思考...

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?

推荐答案

我希望真正的答案很简单:没有一个良好的用例。对于情况下,其优点是,它使在现有各类能说一口流利的API(即本身不提供逻辑) - 即

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) - i.e.

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



这使得LINQ:

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.

这篇关于C#扩展方法体系问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 17:15