当你使用扩展方法,分机。方法与继承? [英] When do you use extension methods, ext. methods vs. inheritance?

查看:150
本文介绍了当你使用扩展方法,分机。方法与继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们开始使用C#(.NET 3.0),我想知道你们是使用扩展方法?当你使用它们?

We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?

另外,我想AP preciate如果你还列出所有黑暗prerequisites使用它们。

Also, I would appreciate if you also list all dark prerequisites for using them.

推荐答案

扩展方法允许现有的类可以不依赖于继承或有更改类的源$ C ​​$ C扩展。这意味着,如果你想添加一些方法到现有的String类,你可以很容易地做到这一点。这里有一对夫妇的规则是否不使用扩展方法决定时要考虑的:

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:

  • 扩展方法不能用来替代现有的方法

  • 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!

这篇关于当你使用扩展方法,分机。方法与继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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