简体   繁体   English

静态类VS私有构造函数

[英]Static Class VS Private Constructor

Today, I have been reading about static class and private constructor. 今天,我一直在阅读静态类和私有构造函数。

Static Class - We cannot create an instance on the static class. 静态类 - 我们无法在静态类上创建实例。 we cannot inherit the static class. 我们不能继承静态类。 Only single instance is generated. 仅生成单个实例。

Private Constructor - We cannot create an instance. 私有构造函数 - 我们无法创建实例。 We cannot inherit. 我们不能继承。 (I Don't know about how many instance is generated.) (我不知道生成了多少个实例。)

I created two console application ie One for static Class, One for Private constructor. 我创建了两个控制台应用程序,一个用于静态类,一个用于私有构造函数。

Static Class Code 静态类代码

在此输入图像描述

I understood single object in generated as constructor is called once. 我理解生成的单个对象作为构造函数被调用一次。

Private Constructor Code 私有构造函数代码

在此输入图像描述

Now, I didn't understand that whether any object is generated or not. 现在,我不明白是否生成了任何对象。

I have two question. 我有两个问题。

Question 1. I didn't find any particular difference between Private constructor and Static class. 问题1.我没有发现Private构造函数和Static类之间有任何特别的区别。 Can you please suggest me that in which scenario where I should use Private Constructor and where should I use Static class as I can use both of them. 你能告诉我在哪种情况下我应该使用Private Constructor,我应该在哪里使用Static类,因为我可以使用它们。

Question 2. If I use private constructor, how many objects is generated? 问题2.如果我使用私有构造函数,会生成多少个对象?

Thanks. 谢谢。

EDIT : 编辑:

I think that people didn't understand my question. 我认为人们不理解我的问题。 I know that static constructor always call once on the first reference. 我知道静态构造函数总是在第一个引用上调用一次。 Static constructor is used to initialize static members of the class. 静态构造函数用于初始化类的静态成员。

Question 1. I have a situation : I need to create a class which cannot be instantiated.I can do this by either static class or private constructor. 问题1.我有一种情况:我需要创建一个无法实例化的类。我可以通过静态类或私有构造函数来完成。 So my question is that "Is there any difference between both of them? which one I should use??" 所以我的问题是“两者之间有什么区别吗?我应该使用哪一个?”

Question 2. If I use private constructor, how many object is created? 问题2.如果我使用私有构造函数,创建了多少个对象? If answer is 0 then how private constructor's memory allocation works in the CLR. 如果answer为0,则私有构造函数的内存分配在CLR中如何工作。 There is no memory allocation if I use private constructor. 如果我使用私有构造函数,则没有内存分配。

Both of you examples you are calling static methods the difference between the two is that the first method is being called within a static class which cannot be instantiated. 您调用static方法的两个示例之间的区别在于第一个方法是在static类中调用的,无法实例化。 The second class could be instantiated however you did not choose to. 第二类可以实例化,但是你没有选择。

The static constructor in the first example is run automatically at runtime when it is needed, it is generally only run once. 第一个示例中的static构造函数在需要时在运行时自动运行,通常只运行一次。

The private constructor is never run as you never instantiated a testPrivateConstructor object. private构造函数永远不会运行,因为您从未实例化过testPrivateConstructor对象。 not because it is private . 不是因为它是private

The Edit: 编辑:

Q1: If you need a class that cannot be instantiated use a static class. Q1:如果需要一个无法实例化的类,请使用static类。 Only use a private constructor instead of a static class if you need to initialise static members (or a singleton pattern). 如果需要初始化静态成员(或单例模式),则仅使用private构造函数而不是static类。

Q2: If you use a private constructor you can instantiate an instance of your class within the class itself so the number of objects that are created depend on how many times you instantiate new objects. Q2:如果使用private构造函数,则可以在类本身中实例化类的实例,因此创建的对象数取决于实例化新对象的次数。

your mixing up a few different things here 你在这里混合了几件不同的东西

a static class public static class MyClass can only contain static elements and never be initialised 静态类public static class MyClass只能包含静态元素,永远不会被初始化

a constructor (whether public or private) always creates in instance of the class the public or private only says the visibility of the constructor. 构造函数(无论是公共的还是私有的)总是在类的实例中创建,public或private只表示构造函数的可见性。

this is commonly used when implementing a singleton design 这在实现单例设计时通常使用

private MyClass()
{
}
private static MyClass _Singleton;
public static MyClass Singleton
{
    get
    {
        if(_Singleton==null) _Singleton = new MyClass();
        return _Singleton
    }
}

} }

the other is a Class Initialiser, this is a little confusing because its syntax is very similar to a constructor baring the adding of a static keyword and lack of parameters 另一个是类初始化器,这有点令人困惑,因为它的语法非常类似于构造函数禁止添加静态关键字和缺少参数

static MyClass()
{
    //configure static variables on first us only
    b = //read value from file or other resource not avalable at compile time
    a = b.Lenth; //can't be be done in class body as b would not have been initialised yet
}
private static int a;
private static string b;

ergo if your class can't be instantiated then you can only declare is as static nothing else will do that, 如果您的类无法实例化,那么您只能声明为静态没有其他人会这样做,

if you call a private constructor then every call creates an instance 如果你调用私有构造函数,那么每个调用都会创建一个实例

a class initialiser can never be called its fired automatically on the first use of a class and does not create an instance 在第一次使用类时,类初始化器永远不会被称为自动触发,并且不会创建实例

EDIT: here is a revised version of your test program 编辑:这是您的测试程序的修订版本

public static class StaticClassExample
{
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function")
    }
}
public static class InitialisedStaticClassExample
{
    static InitialisedStaticClassExample()
    {
        Console.WriteList("This class has been initialised")
    }
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function")
    }
}
public class PrivateConstuctorClassExample
{
    static PrivateConstuctorClassExample()
    {
        Console.WriteList("This class has been initialised")
    }
    private PrivateConstuctorClassExample()
    {
        Console.WriteList("This class has been Instantiated")
    }
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function");
        var instance = new PrivateConstuctorClassExample();
        instance.InstanceFunction();
    }
    public void InstanceFunction()
    {
        Console.WriteList("This is a instance function")
    }
}
  • Static constructor will be called first time when the class is referenced. 引用类时将首次调用静态构造函数。 Static constructor is used to initialize static members of the class. 静态构造函数用于初始化类的静态成员。
  • In the non static class the private or public constructor will not be called. 在非静态类中,不会调用私有或公共构造函数。 Static members will not be initialized either by private or public constructor. 静态成员不会由私有或公共构造函数初始化。

    see the below exmaple 见下面的例子

      class Program { static void Main(string[] args) { OnlyOne.SetMyName("I m the only one."); //static constructor will be called first time when the class will be referenced. Console.WriteLine(OnlyOne.GetMyName()); NoInstance.SetMyName("I have private constructor"); //No constructor will be called when the class will be referenced. Console.WriteLine(NoInstance.GetMyName()); Console.Read(); } } static class OnlyOne { static string name; /// <summary> /// This will be called first time when even the class will be referenced. /// </summary> static OnlyOne() { name = string.Empty; Console.WriteLine("Static constructor is called"); } public static string GetMyName() { return name; } public static void SetMyName(string newName) { name = newName; } } public class NoInstance { static string name; private NoInstance() { name = string.Empty; Console.WriteLine("No instance private constructor is called"); } public static string GetMyName() { return name; } public static void SetMyName(string newName) { name = newName; } } } 

Question 2: 0 问题2:0

Question 1: you created a static class with a static constructor, but you do not need the instance in your case, since the method is static too and the only thing you need to run a static method is the class definition - no instance. 问题1:您使用静态构造函数创建了一个静态类,但在您的情况下您不需要该实例,因为该方法也是静态的,并且运行静态方法所需的唯一事情是类定义 - 没有实例。

your second class works also without construction of an instance - the static method does not need one. 你的第二个类也可以在不构造实例的情况下工作 - 静态方法不需要一个。 and since this is a private constructor only class methods could create the instance. 由于这是一个私有构造函数,因此只有类方法可以创建实例。 you would use the private constructor only in case of the singleton pattern i guess - without a local caller for private constructor it is rather useless. 你只会在我猜的单例模式的情况下使用私有构造函数 - 没有私有构造函数的本地调用者它是相当无用的。

Constructor of a class is called upon creation of instance of the class. 在创建类的实例时调用类的构造函数。 Static constructors are called on initialization of the class. 在初始化类时调用静态构造函数。 Read this 这个

In example 1, your static constructor is initialized the as you are accessing a static method of the class. 在示例1中,当您访问类的静态方法时,将初始化静态构造函数。 This is relevant for a static or non-static class. 这与静态或非静态类相关。

In example 2, your private constructor isn't static. 在示例2中,您的私有构造函数不是静态的。 Your constructor wasn't called as there was no instance created. 由于没有创建实例,因此未调用构造函数。 It has to be called by creating an instance of the class. 必须通过创建类的实例来调用它。

Private constructors are used to control the construction and destruction of the instance of the class. 私有构造函数用于控制类实例的构造和销毁。 Since, only the class can call its constructor in this case. 因为,在这种情况下,只有类可以调用它的构造函数。 You need a static method to get the instance of the class 您需要一个静态方法来获取类的实例

For example, 例如,

public class TestPrivateConstructor
{

private TestPrivateConstructor()
{
  Console.WriteLine("Instance is created, Private Constructor called");
}

static TestPrivateConstructor _instance;

public static TestPrivateConstructor GetInstance()
{
    if(_instance == null)
    {
       _instance = new TestPrivateConstructor();
    }
    return _instance;
}

public static void DisposeInstance()
{
   if(_instance !=null)
   {
      _instance.Dispose();
      _instance = null;
   }
}
public void TestMethod()
{
  Console.WriteLine("Test MEthod Called");
}
void Dispose()
{
 //Do something
}
}

For the code above, try using this. 对于上面的代码,请尝试使用此代码。 Now your private constructor is called as you created an instance. 现在,在创建实例时调用私有构造函数。

class Program
{
   public static void Main(string[] args)
   {
     //Private constructor
     TestPrivateConstructor.GetInstance()
   }
}

Using the approach above, you can control the construction and destruction of the object. 使用上述方法,您可以控制对象的构造和销毁。 If you still have any questions, please feel free to ask. 如果您还有任何疑问,请随时提出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM