“谨慎使用扩展方法"背后的动机是什么? [英] What is the motivation behind "Use Extension Methods Sparingly?"

查看:73
本文介绍了“谨慎使用扩展方法"背后的动机是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现它们是扩展现有类的非常自然的方式,尤其是当您只需要将某些功能点焊"到现有类上时.

I find them a very natural way to extend existing classes, especially when you just need to "spot-weld" some functionality onto an existing class.

Microsoft说:通常,我们建议您仅在必要时谨慎地实施扩展方法.然而,扩展方法构成了Linq的基础.实际上,Linq是创建扩展方法的原因.

Microsoft says, "In general, we recommend that you implement extension methods sparingly and only when you have to." And yet extension methods form the foundation of Linq; in fact, Linq was the reason extension methods were created.

是否存在特定的设计标准,在这些标准中,将使用扩展方法视为继承或组合吗?他们劝阻他们什么条件?

Are there specific design criteria where using extension methods are perferred over inheritance or composition? Under what criteria are they discouraged?

推荐答案

我们向C#MVP显示了建议的新语言功能(至少有一半的机会可以看到日光).我们在许多功能上经常收到的一些反馈是:" I 会根据该功能的设计原则明智地使用此功能,但是我的足球同事打算对此事发疯,并编写大量无法维护的,不可理解的代码,在接下来的十年中,我将陷入调试的困境,所以,只要我想要的话,请永远不要实现此功能!"

We show proposed new language features (at least the ones that have a halfway decent chance of seeing the light of day) to the C# MVPs for early feedback. Some feedback we get very often on many features is "well I would use this feature judiciously and in accordance with the design principles of the feature, but my goofball coworkers are going to go crazy nuts with this thing and write up a mass of unmaintainable, non-understandable code that I'm going to get stuck with debugging for the next ten years, so as much as I want it, please never implement this feature!"

尽管我出于喜剧效果有些夸张,但这是我们非常重视的事情;我们希望新功能的设计能够鼓励它们的使用,但不鼓励滥用它们.

Though I am exaggerating somewhat for comedic effect, this is something we take very seriously; we want the design of new features to encourage their use but discourage their misuse.

我们担心扩展方法将用于例如任意地扩展对象",从而创建松散类型的泥浆大球,这些球很难理解,调试和维护.

We worried that extension methods would be used to, for example, indiscriminantly extend "object" arbitrarily and thereby create big balls of loosely typed mud that would be hard to understand, debug and maintain.

我个人特别关心您在流畅"编程中看到的可爱"扩展方法.像

I'm personally in particular concerned about "cute" extension methods that you see in "fluent" programming. Stuff like

6.Times(x=>Print("hello"));

好在C#中,"for"循环是可以普遍理解和惯用的. 别可爱.

Yuck. "for" loops are universally understandable and idiomatic in C#; don't get cute.

这篇关于“谨慎使用扩展方法"背后的动机是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆