C#密封类与无公共构造函数 [英] C# sealed class vs. no public constructor

查看:109
本文介绍了C#密封类与无公共构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试更深入地了解.NET框架.我想知道是否可以创建两个CommandManager时遇到错误:

I am currently trying to get deeper into the .NET framework. I ran across an error while I was wondering if I could create two CommandManagers:

Cannot create an instance of CommandManager because it has no public constructors.

显然,这意味着:不要这样做,并且拥有两个可能甚至没有意义. 现在,在出现消息之前,我遇到了另一个错误:

Obviously it means: don't do it, and it might not even make sense to have two of them. Now I came across an other error before with the message:

Cannot create an instance of ... because it is sealed

禁止的效果相同,但有什么区别.为什么选择一个没有公共构造函数的类而不是密封它?

The effect is the same in prohibiting but what is the difference. Why does one choose a class to have no public constructors vs making it sealed?

对不起,我病了几天.此外,我混合了两种语言:VB和C#.我打开了两个选项卡,却忽略了一个站在C#上,一个站在VB代码上.一类是密封的,另一类似乎是不可继承的.我没有意识到这实际上是相同的.现在,错误消息引起了人们的注意.

Sorry I was ill for a couple of days. Further I mixed two languages: VB and C#. I had two tabs open and overlooked that one was standing on C# and one on VB Code. One class was sealed the other seemed to be NonInheritable. I didn't realize that this is actually the same. Now the error messages make sens.

IronPython代码段:

IronPython Code snippet:

commandManager = CommandManager()

失败

Cannot create instances of CommandManager because it has no public constructors

同时

class MyCommandManager(CommandManager):
    return super(MyCommandManager, self).__init__(*args, **kwargs)()

失败:

cannot derive from System.Windows.Input.CommandManager because it is sealed

我被这些错误消息误导了,并且由于我的Google和stackoverflow搜索未返回任何答案(自然是因为CommandManager始终在C#中密封,而在VB中始终是NonInheritable) 进一步的CommandManager似乎既密封又没有公共构造函数.

I was mislead by these errormessages and since my google and stackoverflow search returned no answer (naturally because CommandManager is always sealed in C# while always NonInheritable in VB) Further CommandManager seems to be both sealed and having no public constructor.

推荐答案

您密封一个类以防止其被子类化.您删除公共构造函数以防止直接实例化类,通常将其作为单例模式的一部分.

You seal a class to prevent it from being subclassed. You remove public constructors to prevent a class from being directly instantiated, usually as part of a singleton pattern.

您当然可以将两者结合在一起.

You can, of course, combine both.

这篇关于C#密封类与无公共构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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