static Vs类与私有构造函数 [英] static Vs class with private constructor

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

问题描述

我非常喜欢google net ..并且对一件事情有些困惑....





密封类 - 可以不继承这些类但是创建实例



静态类 - 不能创建实例而不能继承它们



具有私有构造函数的类 - 无法在类外创建实例。并且不能继承它们



抽象类 - 不能创建实例但是作为基类继承。





比使用私有构造函数的类时静态类中有相同的行为。只是我们在类中使用私有构造函数创建类的实例..



任何人都可以清除它

i have google net very much .. and have some confusion about one thing ....


sealed class- can not inherit these class but create instances

static class- can not create instance and can not inherit them

class with private constructor - can not create instances outside the class . and can not inherit them

abstract class - can not create instance but inherit as a base class .


than whats the use of class with private constructor when same behavior is available in static class . is it only that we create instance of class with private constructor inside the class ..

can any one clear it

推荐答案

当你可以通过静态方法获取具有私有构造函数的类的实例时,你无法获得静态类的实例。

私有构造函数,例如,在 Singleton 设计模式(参见在C#中实现Singleton [ ^ ])。
You can't get an instance of a static class while you can get instances of a class having private constructor via static methods.
Private constructor is used, for instance, in the Singleton design pattern (see, for istance "Implementing Singleton in C#"[^]).


区别在于。



带私人建设者的班级: -



1.您仍然可以使用另一个公共构造函数来实例化该类。

2.每次实例化时都会调用私有构造函数。



静态等级: -



1.你可以牛逼实例化的。

2.当类加载到内存中时,静态构造函数只调用一次。或者首先引用。
Here is the difference.

Class with private constructor:-

1. You can still have another public constructor to instantiate the class.
2. Private construtor is called every time class has been instantiated.

Static Class:-

1. You cann't instantiate at all.
2. Static constructor is called only once while class is loaded into the memory. or referenced first.


你无法利用所有继承之美的好处,但能够通过使用私有构造函数和静态公共属性(即单例)来实现相同的效果。
You can't avail the benefits of all beauty of inheritance but able to achieve the same by using private constructor with static public property (i.e. singleton).


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

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