C# 你什么时候使用扩展方法,ext。方法与继承?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/787324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When do you use extension methods, ext. methods vs. inheritance?
提问by
We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
我们开始使用 C# (.NET 3.0),我想知道你们是如何使用扩展方的?你什么时候使用它们?
Also, I would appreciate if you also list all dark prerequisites for using them.
另外,如果您还列出使用它们的所有黑暗先决条件,我将不胜感激。
采纳答案by
Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:
扩展方允许扩展现有类,而无需依赖继承或更改类的源代码。这意味着如果你想在现有的 String 类中添加一些方,你可以很容易地做到。在决定是否使用扩展方时,需要考虑以下几条规则:
Extension methods cannot be used to override existing methods
An extension method with the same name and signature as an instance method will not be called
The concept of extension methods cannot be applied to fields, properties or events
Use extension methods sparingly....overuse can be a bad thing!
扩展方不能用于覆盖现有方
与实例方具有相同名称和签名的扩展方将不会被调用
扩展方的概念不能应用于字段、属性或
谨慎使用扩展方......过度使用可能是一件坏事!
回答by Marc Gravell
Times to use extension methods:
使用扩展方的时间:
- when you don't control the types being extended
- where you don't want to force the implementor to provide code that can be done using the existing methods
- 当您不控制要扩展的类型时
- 您不想强迫实现者提供可以使用现有方完成的代码
For an example of the second point; you might have an extension method on IList<T>
(for example, Sort
) that can be written entirely using the existing IList<T>
members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide muchmore functionality without breaking anything.
以第二点为例;您可能在IList<T>
(例如,Sort
)上有一个可以完全使用现有IList<T>
成员编写的扩展方……那么为什么要强迫其他人编写任何东西呢?这是LINQ的基础块,并允许微软提供多不破坏任何东西更多的功能。
Times to notuse extension methods:
时报以不使用扩展方:
- when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
- when you need access to private/protected members
- 当多态性很重要时;您不能保证您的代码将是使用扩展方执行的版本,因为直接在类型上的方优先
- 当您需要访问私人/受保护成员时
回答by Randolpho
I use extension methods when it makes sense. If you control a class and its code, you usually don't need extension methods.
我在有意义的时候使用扩展方。如果你控制一个类及其代码,你通常不需要扩展方。
If you don't, an extension method might be useful.
如果不这样做,扩展方可能会很有用。
One place I frequently use extension methods is for [Flags] enumerations. When you have a flag-based enumeration, there's a rather large expression that's necessary to determine whether or not an enumeration value has a particular flag set. And so I build the following extension method whenever I build a [Flags] enumeration:
我经常使用扩展方的一个地方是 [Flags] 枚举。当你有一个基于标志的枚举时,需要一个相当大的表达式来确定一个枚举值是否有一个特定的标志集。因此,每当我构建 [Flags] 枚举时,我都会构建以下扩展方:
[Flags]
public enum MyEnum
{
FlagA,
FlagB,
// etc.
}
public static class MyEnumExt
{
public static bool HasFlags(this MyEnum item, MyEnum query)
{
return ((item & query) == query);
}
}
That way my code looks like:
这样我的代码看起来像:
MyEnum flags = MyEnum.FlagA;
if(flags.HasFlags(MyEnum.FlagA))
{
// handle FlagA
}
Rather than:
而不是:
MyEnum flags = MyEnum.FlagA;
if((flags & MyEnum.FlagA) == MyEnum.FlagA)
{
// handle FlagA
}
回答by user3395318
This link http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/26/c-extension-methods---to-extend-or-not-to-extend.aspxprovides good guidance on when to use Extension methods and when not.
此链接http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/26/c-extension-methods---to-extend-or-not-to-extend.aspx 为何时使用扩展方提供了很好的指导当没有时。
To quote from this article:
引用这篇文章:
A good extension method should:
- Apply to any possible instance of the type it extends.
- Simplify logic and improve readability/maintainability.
- Apply to the most specific type or interface applicable.
- Be isolated in a namespace so that it does not pollute IntelliSense.
一个好的扩展方应该:
- 适用于它扩展的类型的任何可能的实例。
- 简化逻辑并提高可读性/可维护性。
- 适用于最具体的类型或适用的接口。
- 在命名空间中隔离,以免污染 IntelliSense。
回答by Rober
Honestly, I would say it is easier to explain when it is NOTa good idea than when it is a good idea.
老实说,我会说当它不是一个好主意时比当它是一个好主意时更容易解释。
I think, the main benefit to extension methods is that they may increase the adoption of your method. This is because the user will not have to instantiate an instance of another class in order to use your method and intellisense will advertise your method when a developer is looking for methods for the class you are extending. This could be important if you are trying to get other developers to follow a new standard in your company.
我认为,扩展方的主要好处是它们可能会增加您的方的采用率。这是因为用户不必为了使用您的方而实例化另一个类的实例,并且当开发人员为您正在扩展的类寻找方时,intellisense 会宣传您的方。如果您试图让其他开发人员遵循贵公司的新标准,这可能很重要。
When contemplating whether or not to create an extension method, remember the SOLIDprinciples.
在考虑是否创建扩展方时,请记住SOLID原则。
Single Responsibility: - You are almost always at least bending the single responsibility principle with an extension method because you are tacking on to something that is already a class (that you either don't have control over or are too afraid to touch).
Open/Close Principle: - Extension methods cannot be overridden, which means your method may not be adequately "open for extension".
Liskov substitution principle: - If you have any sort of inheritance structure you will not be able to use the extension methods on the sub types.
Interface segregation principle: - Although you can "extend" an interface, you have to provide a concrete implementation for that extension. So you can not program towards an interface >that can be implemented differently in a different context (eg Unit Test)
Dependency inversion principle: - If your code has any dependencies, how are you going to expose those dependencies for factories and unit tests (dependency inversion principle)?
小号英格尔责任: -你几乎总是至少有一个扩展方弯曲单一职责原则,因为你在套结的东西,已经是一个类(你要么不拥有控制权或过于害怕触摸)。
开放/关闭原则: - 扩展方不能被覆盖,这意味着你的方可能没有充分地“为扩展开放”。
Liskov 替换原则: - 如果您有任何类型的继承结构,您将无在子类型上使用扩展方。
我覆盖整个院落隔离原则: -尽管你可以在“扩展”的界面,你必须提供该扩展名的具体实现。因此,您无针对可以在不同上下文中以不同方式实现的接口进行编程(例如单元测试)
dependency倒置原则: -如果您的代码有任何相关性,你怎么揭露工厂和单元测试(依赖倒置原则),这些依赖?
Finally, extension methods are just static methods wearing a new dress. So all of the difficulties with static methods (such as thread safety, garbage collection, etc) come along with extension methods when you implement them.
最后,扩展方只是穿着新衣服的静态方。因此,当您实现扩展方时,静态方(例如线程安全、垃圾收集等)的所有困难都伴随着它们。
So, I would think long and hard about writing a method as an extension and reconsider using a factory and a basic helperclass instead.
因此,我会认真考虑将方编写为扩展并重新考虑使用工厂和基本帮助程序类。
If you do write an extension method, please make it very simple. Try to avoid having any dependencies (or pass all of your dependencies in as parameters). And be careful for how you manage memory and lock resources in a multi-threaded environment.
如果您确实编写了扩展方,请使其非常简单。尽量避免有任何依赖项(或将所有依赖项作为参数传入)。并注意在多线程环境中如何管理内存和锁定资源。
回答by AutomationNerd
What are extension methods?
什么是扩展方?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
扩展方使您能够向现有类型添加方,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
扩展方是一种特殊的静态方,但它们被称为扩展类型的实例方。
How to use extension methods?
如何使用扩展方?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
扩展方是静态类的静态方,其中“this”修饰符应用于第一个参数。第一个参数的类型将是扩展的类型。
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
仅当您使用 using 指令将命名空间显式导入源代码时,扩展方才在范围内。
Important points for the use of extension methods:
使用扩展方的要点:
1.An extension method must be defined in a top-level static class.
1.扩展方必须定义在顶级静态类中。
2.An extension method with the same name and signature as an instance method will not be called.
2.与实例方具有相同名称和签名的扩展方将不会被调用。
3.Extension methods cannot be used to override existing methods.
3.扩展方不能用于覆盖现有方。
4.The concept of extension methods cannot be applied to fields, properties or events.
4.扩展方的概念不能应用于字段、属性或。
5.Overuse of extension methods is not a good style of programming.
5.过度使用扩展方不是一种好的编程风格。