在C#和.NET Framework中使用私有构造函数有什么用? [英] What is the use of a Private Constructors in C# and .NET Framework?

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

问题描述

有人可以解释一下在C#中最好使用私有构造函数,或者在什么情况下应该使用私有构造函数?

解决方案

扩展OG的帖子...



您也可以使用它们在其他构造函数之前初始化一些标准字段集,例如:



< pre lang =cs> public class 示例
{
int x,y,z;
string name;
bool 标志;

private Sample()
{
x = 5 ;
y = 10 ;
z = 15 ;
flag = true ;
}

public 示例( string 名称)
()
{
// flag,x,y和z在这里初始化
name = Name;
}

public 示例(字符串名称, bool 标志)
(名称) // 构造函数链接
{
// name,flag,x,y和z在这里初始化,但是我们需要更改标志
this .flag =旗;
}
}





这样,您减少了代码的重复,并确保只有一个地方如果您必须更改字段的默认值。是的,你可以在定义变量时正确执行此操作,但有些情况下你不能或想要更多的逻辑来初始化它们。



然后你只能使用用于创建对象的公共构造函数,例如:



示例s1 =  new 示例(  BlahBlah); 
示例s2 = new 示例( BlahBlooBlee false );


Ron和OriginalGriff的优秀答案以上。请投票给他们的答案,而不是这个:)



请记住,所有C#类定义都创建一个没有参数的(不可见)默认公共构造函数。 br />


默认的构造函数,在被激发时,会将所有Class字段的值设置为Type的默认值。



在早期版本的C#中,没有参数的私有类构造函数通常与标记为密封的类一起使用,而类被用作静态方法集合的主机。这种类型被称为实用类。



为什么类标记为密封:防止有人试图从类中获得。 />


早期版本的C#为您定义了默认的构造函数,如果您自己没有提供。因此,编写一个无参数的私有构造函数是确保类永远无法实例化的一种方法。



后来的C#版本替换了这些笨拙的约束,能够定义静态类:使用静态类,您不再需要编写私有构造函数,不需要标记它们'密封等等。



私有构造函数可以有参数吗?是。你可能会这样做,如果你有一些理由有一个间接的水平,其中你永远希望直接从外面类的一个实例。



要实现你要实现某种形式的公共构造函数,或者创建类的实例并接受参数的公共方法,然后调用私有构造函数,或者,如Ron所示,您可以使用Private Constructor初始化一些私有变量。这是一个罕见的案例;你可以在Jon Skeet的C#In Depth Third Edition中找到这种类定义的例子。 449,代码清单14.29。


私有构造函数意味着无法从类外部实例化类:创建类实例的唯一方法是调用 static 类中创建实例的方法,或返回对现有实例的引用。



通常,它们被使用在 singleton 设计模式中,代码确保只能创建一个类的实例。



请参见 http://en.m.wikipedia.org/wiki/Singleton_pattern [ ^ ]了解更多信息。


Can Someone Explain whats best use of Private Constructors in C# or in what scenario should Private Constructors be used?

解决方案

Expanding on OG's post...

You can also use them to initialize some standard set of fields before other constructors, for example:

public class Sample
{
    int x, y, z;
    string name;
    bool flag;

    private Sample()
    {
        x = 5;
        y = 10;
        z = 15;
        flag = true;
    }

    public Sample(string Name)
       : this()
    {
        //flag, x, y, and z are initialized here
        name = Name;
    }

    public Sample(string Name, bool flag)
       : this(Name)   //Constructor chaining
    {
        //name, flag, x, y, and z are initialized here, but we need to change flag
        this.flag = flag;
    }
}



That way, you reduce repetition of code and make sure that there is only one place if you have to change the default values of the fields. Yes you can do this right when you define the variables but there are instances when you can't or want more logic to initializing them.

Then you can only use the public constructor to create the object, like:

Sample s1 = new Sample("BlahBlah");
Sample s2 = new Sample("BlahBlooBlee", false);


A minor addition to Ron and OriginalGriff's excellent answers above. Please vote for their answers, not this one :)

Keep in mind that all C# Class definitions create a ("invisible") default Public Constructor with no parameters.

That default Constructor, when evoked, will set the value of all Class fields to their Type's default values.

In early versions of C#, a Private Class Constructor with no parameters was often used with the Class marked as 'Sealed, and the Class was used as a "host" for a collection of Static methods. This type of Class is referred to as a "Utility Class."

Why was the Class marked 'Sealed: to prevent someone attempting to derive from the Class.

Early versions of C# defined a default Constructor for you, if you did not supply one yourself. So, writing a parameterless Private Constructor was a way to make sure the Class could never be instantiated.

Later versions of C# replaced these awkward constraints with ability to define Static Classes: with a Static Class you no longer had to write a Private Constructor, didn't need to mark them 'Sealed, etc.

Can a Private Constructor have Parameters ? Yes. You might do that if you had some reason to have a level of indirection where there were Private variables (or whatever) in the Class that you never wanted set directly from outside an instance of the Class.

To implement that you would implement some form of Public Constructor, or Public Method that created an instance of the Class and did accept Parameters, and then call the Private Constructor, or, as Ron showed, you could just use the Private Constructor to initialize some Private variables. This is a rare case; you can find an example of this type of Class definition in Jon Skeet's "C# In Depth Third Edition," p. 449, Listing 14.29.


A private constructor means that the class can't be instantiated from outside the class: the only way to create an instance of the class is by calling a static method within the class which creates an instance, or returns a reference to an existing instance.

Generally, they are used in singleton design patterns, where the code ensures that only one instance of a class can ever be created.

See http://en.m.wikipedia.org/wiki/Singleton_pattern[^] for more info.


这篇关于在C#和.NET Framework中使用私有构造函数有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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