停止或避免继承 [英] Stop or avoid inheritance

查看:123
本文介绍了停止或避免继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何避免继承父类,除了Sealed类还有其他方法吗?
请通过示例给我..

How can I avoid inheritance of parent class ,is there any other way except Sealed class?
kindly give me through example..

推荐答案

好吧,结构是隐式密封的,因此请使用结构而不是类.愚蠢的面试问题.
Well, structs are implicitly sealed so use a struct not a class. Stupid interview question.


好!您让我感兴趣,如果可以解决的话,我想出了两种解决方案:
第一个通过在运行时进行检查来工作,并依赖于这样的事实,即在实例化派生类的实例时也会调用基类的构造函数(至少是默认构造函数).

Ok! You''ve got me interested if it could be done and I came up with 2 solutions:
The first one works by doing a check at runtime and relies on the fact that a constructor (at least the default constructor) of the base class is also called when an instance of the derived class is instantiated.

namespace Some.Name.Space
{
    public class A
    {
        private static Type myType = new A().GetType(); // You need this in your class

        int idx;
        public A()
        {
            if(myType!=null) // Do this in every constructor of your class
                checkType(this);
            this.idx = 0;
        }

        public A(int idx)
        {
            if(myType!=null) // Do this in every constructor of your class
                checkType(this);
            this.idx = idx;
        }

        public int a { get {return a;} set{idx = value;} }

        private void checkType(Object obj) // And this method makes sure only base class instantiations are allowed
        {
            if(myType != obj.GetType())
                throw new Exception(String.Format("I'm a {0} and you're a {1}. This ain't gonna work, sorry.", myType, obj.GetType()));
         }
    }
}



2.解决方案是将所有构造函数设为私有,并且仅允许通过静态工厂方法进行实例化,这将使得无法从此类派生.


免责声明

我真的不明白为什么有人会使用第一个解决方案,但是第二个解决方案确实一次或一次都有其优点,即使它的目的是 NOT 试图模仿密封的关键字.
毕竟这只是出于好奇而做的,希望这次的努力不会太糟. (正如我希望OP的问题也如此:))


问候,


曼弗雷德(Manfred)



2. solution is to make all constructors private and allow instantiation only through static factory methods, this will make it impossible to derive from this class.


Disclaimer

I don''t really see why anybody would want to use the first solution, but the second one does have its merits at one time or the other, even if its purpose is NOT trying to emulate the sealed keyword.
Hope the thrashing won''t be to bad, after all this was only done out of curiosity. (As I hope was also the case for OP''s question :) )


Regards,


Manfred


我能想到的另一种方法是将其放入其自己的组件中并制成internal.但是到那时,您根本无法从其程序集外部使用它.
The ony other way I can think of right off hand is putting it into it''s own assembly and making it internal. But at that point, you can''t use it at all from outside its assembly.


这篇关于停止或避免继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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