覆盖扩展方法 [英] Overriding Extension Methods

查看:115
本文介绍了覆盖扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在思考如何使用扩展方法作为一个抽象基类的替代品。扩展方法可以提供默认功能,并通过把相同的签名方法在派生类中可以覆盖。

I've been thinking about using extension methods as a replacement for an abstract base class. The extension methods can provide default functionality, and can be 'overridden' by putting a method of the same signature in a derived class.

任何理由,我不应该这样做?

Any reason I shouldn't do this?

另外,如果我有相同的签名,两拓方法,其中之一是使用?是否有建立一个优先的方式?

Also, if I have two extension methods with the same signature, which one is used? Is there a way of establishing priority?

推荐答案

我同意迈克尔。基类应该包含所有基本功能的扩展方法应该很明显,扩展了基本功能。在Ruby等动态语言往往是典型的使用扩展方法来提供另外的功能,而不是使用子类。基本上,扩展方法在那里更换使用subclassses,而不是取代使用基类。

I agree with Michael. Base classes should contain all base functionality Extension methods should, obviously, extend the base functionality. In dynamic languages like Ruby it is often typical to use extension methods to provide addition functionality instead of using subclasses. Basically, extension methods are there to replacing using subclassses, not to replace using base classes.

唯一的例外,我所看到的是,如果你有一个有不同的类hierachies(如WinForm的控制)的多个类型,可以使每一个子类,都实现和接口,然后扩展该接口,从而使基地功能,以一组不同的控件,不延长一切都像控件或对象。

The only exception to this that I've seen is if you have multiple type that have different class hierachies (like winform controls), you can make a subclass of each that all implement and interface and then extend that interface, thereby giving "base" functionality to a group of different controls, without extending everything like Control or Object.

编辑:在回答你的第二个问题

answering your second question

我觉得编译器将抓住这个给你。

I think the compiler will catch this for you.

这篇关于覆盖扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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