C#中私有构造函数的需要是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/920045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the need of private constructor in C#?
提问by devnull
What is the need of private constructor in C#? I got it as a question for a C# test.
C#中私有构造函数的需要是什么?我把它作为一个 C# 测试的问题。
采纳答案by Svish
For example if you have a class that should only be created through factory methods. Or if you have overloads of the constructor, and some of them should only be used by the other constructors. Probably other reasons as well =)
例如,如果您有一个只能通过工厂方法创建的类。或者,如果您有构造函数的重载,并且其中一些应该只由其他构造函数使用。可能还有其他原因=)
回答by Mehrdad Afshari
Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private
constructor. For example, prior to C# 2.0 which introduced static
classes, you used a private
constructor to accomplish roughly the same thing:
每当您想防止从外部直接实例化一个类时,您将使用private
构造函数。例如,在引入static
类的C# 2.0 之前,您使用private
构造函数来完成大致相同的事情:
sealed class StaticClass {
private StaticClass() {
}
public static void DoSomething() {
}
}
回答by Andrew Weir
While this link is related to java, I think it should help you understand the reason why as the idea is pretty much the same.
虽然此链接与 java 相关,但我认为它应该可以帮助您理解原因,因为想法几乎相同。
Private constructors prevent a class from being explicitly instantiated by callers. There are some common cases where a private constructor can be useful:
- classes containing only static utility methods
- classes containing only constants
- type safe enumerations
- singletons
私有构造函数防止类被调用者显式实例化。在一些常见的情况下,私有构造函数很有用:
- 仅包含静态实用程序方法的类
- 只包含常量的类
- 类型安全枚举
- 单身人士
回答by Mike Chaliy
For example when you provide factory methods to control instantiation...
例如,当您提供工厂方法来控制实例化时...
public class Test(){
private Test(){
}
void DoSomething(){
// instance method
}
public static Test CreateCoolTest(){
return new Test();
}
}
回答by Jesper Fyhr Knudsen
When you want to prevent the users of your class from instantiating the class directly. Some common cases are:
当您想阻止类的用户直接实例化类时。一些常见的情况是:
- Classes containing only static methods
- Singletons
- 仅包含静态方法的类
- 单身人士
回答by Mouk
I can can recall few usages for it:
我可以回忆起它的一些用法:
- You could use it from a static factory method inside the same class
- You could do some common work inside it and then call it from other contructure
- You could use it to prevent the runtime from adding an empty contructure automatically
- It could be used (although private) from some mocking and ORM tools (like nhibernate)
- 您可以从同一个类中的静态工厂方法中使用它
- 你可以在里面做一些普通的工作,然后从其他结构中调用它
- 您可以使用它来防止运行时自动添加空结构
- 它可以从一些模拟和 ORM 工具(如 nhibernate)中使用(虽然是私有的)
回答by G B
If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it. An example in Java (I don't know C# well enough, sorry) with a singleton-class:
如果您了解某种设计模式,则很明显:一个类可以在内部创建自己的新实例,而不允许其他人这样做。一个带有单例类的 Java 示例(我不太了解 C#,抱歉):
class Meh
{
private Meh() { }
private static Meh theMeh = new Meh();
public static Meh getInstance() { return theMeh; }
}
回答by RobV
You can use it with inheritance in a case where the arguments to the constructor for the base class are of different types to those of the child classes constructor but you still need the functionality of the base class in the child class eg. protected methods.
在基类的构造函数的参数与子类构造函数的参数类型不同的情况下,您可以将它与继承一起使用,但您仍然需要子类中基类的功能,例如。受保护的方法。
Generally though this should be avoided wherever possible as this is a bad form of inheritance to be using.
一般来说,尽管这应该尽可能避免,因为这是一种不好的继承形式。
回答by ra170
And of course you can use private constructor to prevent subclassing.
当然,您可以使用私有构造函数来防止子类化。
回答by vijay kumar vishwakarma
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.
私有构造函数用于在没有实例字段或方法(例如 Math 类)或调用方法以获取类的实例时阻止创建类的实例。如果类中的所有方法都是静态的,请考虑将整个类设为静态。有关更多信息,请参阅静态类和静态类成员。
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = System.Math.E; //2.71828...
}
The following is an example of a class using a private constructor.
以下是使用私有构造函数的类的示例。
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.Console.WriteLine("New count: {0}", Counter.currentCount);
}
}