为什么不支持 C# 静态类扩展方法? [英] Why aren't C# static class extension methods supported?

查看:35
本文介绍了为什么不支持 C# 静态类扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这个问题中了解到扩展方法只能对类实例进行操作,而不能对静态类本身进行操作.这意味着我不能扩展像 ConvertMath 这样有用的静态类.

I know from this question that extension methods can only operate on class instances, not the static class itself. This means I can't extend useful static classes like Convert and Math.

我想知道的是,为什么会这样?从上面的链接中,有一些关于 C# 团队如何实现这种功能的建议.是否有一些哲学原因不支持它?

What I want to know is, why is this the case? From the link above, there are some suggestions on how the C# team could have implemented this kind of functionality. Is there some philosophical reason why it isn't supported?

例如,这是一个基本原理 背后为什么没有内置 IEnumerable 的 LINQ ForEach 扩展.

For example, here's a rationale behind why there is no built-in LINQ ForEach<T> extension for IEnumerable<T>.

推荐答案

C# 团队本可以实现这种功能.是否有一些哲学原因不支持它?

the C# team could have implemented this kind of functionality. Is there some philosophical reason why it isn't supported?

没有技术原因,也没有哲学原因.然而,正如我经常指出的那样,我不必为做一个功能提供理由.功能并不便宜;它们非常昂贵,他们不仅必须证明自己的成本是合理的,还必须证明不执行我们可以用该预算完成的其他一百项功能的机会成本是合理的.我们必须向我们的利益相关者证明功能成本是合理的,但我们不需要通过实现不符合我们标准的功能来证明节省时间和精力是合理的.

There's no technical reason, and no philosophical reason. However, as I often point out, I don't have to provide a justification for not doing a feature. Features aren't cheap; they are extremely expensive and they must not only justify their own cost, they must justify the opportunity cost of not doing the hundred other features we could have done with that budget. We must justify the cost of features to our stakeholders, but we need not justify saving time and effort by not implementing features that don't meet our bar.

特别是,提议的特性对 LINQ 没有任何作用;添加了扩展方法以使 LINQ 工作.任何不能使 LINQ 工作的东西都很难进入 C# 3.0;我们在日程表上有很多工作,但没有太多时间去做.(我很惊讶自动属性让它进来.)甚至在设计之前删除一个不必要的功能,节省了大量的时间和精力花在其他方面使 LINQ 工作的事情.

In particular, the proposed feature does nothing for LINQ; extension methods were added to make LINQ work. Anything that didn't make LINQ work was very hard to get into C# 3.0; we had a lot of work on the schedule and not much time to do it in. (I was surprised that automatic properties made it in.) Cutting an unnecessary feature before even designing it saved a lot of time and effort that was spent on other things that do make LINQ work.

简而言之:建议的功能从未达到我们的净收益超过成本的标准,而且我们总是有更重要的功能需要花费我们有限的时间和精力.

In short: the suggested feature has never met our bar for net benefit over cost, and we've always had more important features to spend our limited time and effort on.

这篇关于为什么不支持 C# 静态类扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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