简体   繁体   English

扩展方法与常规方法 - 最佳实践思路

[英]Extension Methods vs. Regular Methods - Best Practice Ideas

I'm having a bit of a difficult time determining when to implement a method as an extension method and when to implement a method as a stand-alone method. 我在确定何时将方法实现为扩展方法以及何时将方法实现为独立方法时遇到了一些困难。 What are some best practices people follow in determining this? 人们在确定这一点时会遵循哪些最佳做法?

Use an extension method if any of the following conditions are true: 如果满足以下任一条件,请使用扩展方法:

  • You need a method on a type and you don't own the source. 您需要一个类型的方法,并且您不拥有源。
  • You need a method on a type, you do own the source, and the type is an interface. 你需要一个方法上的类型,你自己的来源,类型是一个接口。
  • You need a method on a type, you do own the source, but adding the method creates undesired coupling.* 你需要在一个类型的方法,你自己的来源,但加入的方法创建不需要的耦合。*

Otherwise, you should use a real method on the actual type itself. 否则,您应该对实际类型本身使用实际方法。

I don't think it makes a whole lot of sense to create an extension method for a class or struct that you own the source for - why confuse readers with an extension method when a regular method will suffice? 我认为为您拥有源代码的类或结构创建扩展方法没有多大意义 - 为什么在常规方法足够时将读者与扩展方法混淆?

Suggested reading: Framework Design Guidelines: Extension Methods 建议阅读: 框架设计指南:扩展方法

* Imagine that you wanted to add convenience methods to a type but don't want to create dependencies to assemblies or types that shouldn't be part of the API. * 想象一下,您希望为类型添加便捷方法,但不希望创建不应该属于API的程序集或类型的依赖项。 You could use extension methods to manage this. 您可以使用扩展方法来管理它。

Try this Stackoverflow post for a discussion about extension method best practices. 试试这篇Stackoverflow文章,讨论扩展方法的最佳实践。

From my perspective I use extension methods when I have a lot of utility functions for a particular type. 从我的角度来看,当我为特定类型提供大量实用函数时,我会使用扩展方法。

I find that... 我发现...

string.ExtensionMethod();

looks cleaner than... 看起来比...更清洁

StringHelper.ExtensionMethod("string to do something with");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM