在不使用“密封关键字"的情况下密封课程 [英] seal a class without using 'Seal keyword'

查看:103
本文介绍了在不使用“密封关键字"的情况下密封课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我必须在不使用"Seal关键字"的情况下封闭类,我将如何实现?

不要说我们可以密封该类的方法.

If I have to seal a class without using ''Seal keyword'', how would I achieve that?

Don''t say that we can seal the methods of that class.

推荐答案


将一个类设置为密封"意味着不能将其用作任何其他类的基类".

如果没有密封"关键字,则可以按照以下方式实现,

1.编写该类的显式构造函数,覆盖系统提供的默认构造函数.
2.将构造函数设为私有".

Hi
To make a class "Sealed" means it can not be served as a "Base class" to any other class(es).

Without "sealed" keyword it can be achived following way,

1. Write an explicit constructor of the class, overwriting default system provided constructor.
2. Make the constructor as "private".

namespace N
{
    class A
    {
        private A()
        {

        }
    }
}


上面的代码与密封的类"等效",这里的A类已被制成密封类,限制了其他类都可以从"A"派生,而不管名称空间是什么.

让我知道是否有帮助,


Above code is "equivalent" to a "sealed class", here class A have been made as sealed class, restricting other class(es) to derive from "A" irrespective of whatever the namespace is.

Let me know if that helps,


因为我想这是一个面试问题-实现此目的的一种方法是创建一个私有类,然后将其用作嵌套类.这样就可以继承该类."

当然,必须有另一个我完全不知道的更好的替代解决方案.
:)
Since I suppose this was an interview question - "One way to do this would be to make a private class and then use it as a nested class. No one can inherit that class then."

Of course, there must be another better alternate solution which I am totally unaware of.
:)


这篇关于在不使用“密封关键字"的情况下密封课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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