我们什么时候需要在类中使用私有和公共构造函数 [英] When do we need both private and public constructor in a class

查看:69
本文介绍了我们什么时候需要在类中使用私有和公共构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 时,我们需要 private  public 构造函数   class ?请解释





我的尝试:



我们何时需要类中的私有和公共构造函数

解决方案

首先,请阅读:[ ^ ]并注意非定义的非静态类构造函数具有为其创建的默认构造函数。然后,请阅读:[ ^ ]。 />


其次,如果你定义一个带有任何非可选参数的构造函数,那就烧掉你的大脑,即任何没有设置默认值的参数在参数列表中,未创建默认的无参数构造函数。



在Visual Studio项目中尝试此代码:

  public   class  MyNoConstructorClass 
{
public string WhoAmI { set ; get ; }
}

public class MyOneParameterConstructorClass
{
public string WhoAmI { set ; get ; }

public MyOneParameterConstructorClass( string whoami = nobody
{
WhoAmI = whoami;
}
}

public class MyTwoParameterConstructorClass
{
public string WhoAmI {设置; get ; }

public string WhatAmI {设置; get ; }

public MyTwoParameterConstructorClass( string whatami,字符串 whoami = nobody
{
WhatAmI = whatami;
WhoAmI = whoami;
}
}

是的,您将收到编译错误:注释掉编译失败的行,然后:



在某些方法或EventHandler中测试它:在第一次调用之前设置一个断点,创建一个'MyNoConstructor实例,然后单步执行(Visual Studio中的F11),通过代码观察发生的情况: pre> MyNoConstructorClass mnc = new MyNoConstructorClass();
mnc.WhoAmI =看,妈,没有构造函数!;

MyOneParameterConstructorClass moc = new MyOneParameterConstructorClass();
moc.WhoAmI =某人定义了默认参数;

MyTwoParameterConstructorClass m2c = new MyTwoParameterConstructorClass(one);

MyTwoParameterConstructorClass m2c2 = new MyTwoParameterConstructorClass(whatami:很奇怪);

MyTwoParameterConstructorClass m2c3 = new MyTwoParameterConstructorClass(whoami:很奇怪);

一般来说:



1.非-static类总是会有一个'公共访问点,导致正在创建一个类的实例......如果不是,你还会创建一个实例?请记住,如上所述,如果您没有创建参数列表语法有效,则默认情况下会创建无参数构造函数。



1.a 。非静态类需要无参数构造函数的情况各不相同。



1.b.在编译器要求你有一个公共无参数构造函数的情况下,通常可以避免使用带有参数的构造函数末尾带冒号前面的'base()指令编写一个。



1.b.1。序列化是编译器可能需要无参数构造函数的一个示例。具体而言,可能会因您使用的序列化程序(XML,JSON,DataContract)而异。我已经读过一些序列化程序可以使用声明为'private的无参数构造函数。我从来没有编写代码来测试它,并且不打算:) Marc Gravell(StackOverFlow大师)声明DataContract序列化程序不需要无参数构造函数。



1.b.1.a.某些外部机构的依赖注入也可能是必须存在无参数构造函数的情况。



1.b.2。一般来说,有人可能会说某个外部实体或某些用法期望/要求它有一个非静态类的无参数公共ctor。



2.静态类有一个可选的静态构造函数,不能声明为'public。当对'静态类或其成员进行任何引用时,它将自动被调用。



3.使用构造函数的非静态类的情况access-type被定义为'private,并使用一个公共静态变量来保存该类的唯一实例,称为Singleton。



4。 'Struct对象的初始化有自己的特点,你应该阅读有关它的文档。


问题不正确,无法回答。从形式上讲,我已经在我对这个问题的评论中解释了你需要知道的关于这个主题的所有内容。当然,您还应该了解构造函数的工作原理以及所有访问修饰符及其用途。您可以在参考文献的相应部分阅读:重定向通知 [ ^ ]。



现在,这种理解应该应用于类的所有成员或 struct ,而不仅仅是构造函数。绝对没有区别。



另一步需要一些逻辑。如果类型是静态的,您可能或者我不需要任何构造函数,但是可能需要静态构造函数,当然,不可能允许实例构造函数,因为没有实例。显然,这样的构造函数将始终是私有的,因为它永远不会被显式调用,而是在第一次使用该类型的任何成员之前调用。



带有非静态类型,有所有选项。这取决于使用情况。创建实例时需要构造函数,因此,如果在同一程序集中使用该类型,则可以使用内部构造函数创建实例。当您需要在其他程序集中创建实例时,需要使用公共程序。请注意,您可能根本不需要任何构造函数,因为使用了默认构造函数(阅读它们)。您可能不需要非私有构造函数,因为您可以使用静态工厂方法来返回同一个类的实例。此方法的实现可以使用私有构造函数。此外,静态(因而私有)构造函数可用于初始化一些静态成员。并且您可以在内部或公共构造函数的实现中使用私有构造函数。无论如何,您可以面对许多不同的需求组合。所以,你必须像我在对这个问题的评论中描述的那样行事。



免责声明:这不是问题的答案。问题不正确;它不能也不应该回答。这只是对该主题需要了解的解释。



-SA


When do we need both private and public constructor in a class? Please explain 



What I have tried:

When do we need both private and public constructor in a class

解决方案

First, read this: [^] and be aware that a non-static Class defined without a constructor has a default constructor created for it. Then, read this: [^].

Second, burn into your brain that if you define a constructor with any non-optional parameter i.e., any parameter that does not have its default value set in the parameter list, that a default parameterless constructor is not created.

Try this code in a Visual Studio Project:

public class MyNoConstructorClass
{
    public string WhoAmI { set; get; }
}

public class MyOneParameterConstructorClass
{
    public string WhoAmI { set; get; }

    public MyOneParameterConstructorClass(string whoami = "nobody")
    {
        WhoAmI = whoami;
    }
}

public class MyTwoParameterConstructorClass
{
    public string WhoAmI { set; get; }

    public string WhatAmI { set; get; }

    public MyTwoParameterConstructorClass(string whatami, string whoami = "nobody")
    {
        WhatAmI = whatami;
        WhoAmI = whoami;
    }
}

Yes, you will get a compile error: comment out the line where compile fails, and, then:

Test it like this in some method or EventHandler: put a break-point before the first call that creates an instance of 'MyNoConstructor, and then single-step (F11 in Visual Studio) through the code observing what happens:

MyNoConstructorClass mnc = new MyNoConstructorClass();
            mnc.WhoAmI = "look, ma, no constructor !";

MyOneParameterConstructorClass moc = new MyOneParameterConstructorClass();
            moc.WhoAmI = "somebody with a default parameter defined";

MyTwoParameterConstructorClass m2c = new MyTwoParameterConstructorClass("one");

MyTwoParameterConstructorClass m2c2 = new MyTwoParameterConstructorClass(whatami: "weird");

MyTwoParameterConstructorClass m2c3 = new MyTwoParameterConstructorClass(whoami: "weird");

In general:

1. non-static classes will always have a 'public access point that results in an instance of the class being created ... how else would you create one if they didn't ? keep in mind that, as described above, a parameterless constructor is created by default if you haven't created one given the parameter list syntax is valid.

1.a. the circumstances in which a non-static class requires a parameterless constructor vary.

1.b. in cases where the compiler demands you have a public parameterless constructor, you can often avoid writing one by using the 'base() directive preceded by a colon at the end of your constructor with parameters.

1.b.1. serialization is one example of when the compiler may demand a parameterless constructor. what happens, specifically, may vary with the serializer you use (XML, JSON, DataContract). I have read that some serializers can work with a parameterless constructor declared as 'private. I've never written code to test that, and don't intend to :) Marc Gravell (StackOverFlow guru) has stated that the DataContract serializer does not require a parameterless constructor.

1.b.1.a. 'dependency injection' by some external agency may also be a case where a parameterless constructor must be present.

1.b.2. in general, one might say that a parameterless public ctor on a non-static class is required when some external entity, or some usage, expects/demands it to have one.

2. static classes have an optional static constructor which cannot be declared 'public. it will be automatically invoked when any reference is made to the 'static class or its members.

3. the case of a non-static class which uses a constructor whose access-type is defined as 'private, and uses a public static variable to hold the one-and-only instance of the class is called a Singleton.

4. the initialization of 'Struct objects has its own characteristics, and you should read the documentation about that.


The question is not correct and cannot be answered. Formally speaking, I already explained all you need to know about the subject in my comment to the question. Of course, you should also know how constructors work and all the access modifiers and their purposes. You can read it in the appropriate part of the reference: Redirect Notice[^].

Now, this understanding should be applied to all the members of a class or a struct, not just to constructors. There is absolutely no difference.

The other step requires some logic. If the type is static, you may or my not need any constructors, but a static constructor can be required and, naturally, an instance constructor could not possibly be allowed, because there are no instances. Apparently, such constructor will be always private, because it is never called explicitly, but is called before any member of the type is first used.

With a non-static type, there all the options. It depends on usage. A constructor is needed when you create an instance, so, if you use the type in the same assembly, an instance can be created with internal constructor. A public one is needed when you need to create an instance in some other assembly. Note that you may not need any constructors at all, because a default constructor is used (read about them). You may need no non-private constructors because you can have a static factory method which returns the instance of the same class. The implementation of this method can use a private constructor. Also, a static (and hence private) constructor can be used to initialize some static members. And you can use a private constructor in the implementation of the internal or public constructor. Anyway, you can face many different combinations of needs. So, you have to act as I described in my comment to the question.

Disclaimer: this is not the answer to the question. The question is incorrect; it cannot and should not be answered. This is just the explanation of what one needs to know on the subject.

—SA


这篇关于我们什么时候需要在类中使用私有和公共构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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