Sealed Class - Why Remove the Public Constructor?
I have a class, the stub of which is shown below. Code analysis gripes if I don't remove the public constructor. But I'm curious why this is necessary on a sealed class? The particular class shown below only contains static methods. Why would it be 开发者_如何学编程good practice to include a private constructor just to remove the public one?
public sealed class ParseFile
{
/// <summary>
/// Remove the public constructor to satisfy CA1053.
/// </summary>
private ParseFile()
{
}
}
If there's only static methods, declare it as a static class, and stop worrying about constructors.
public static class ParseFile
{
}
You're not getting this warning because the class is sealed, but because it is (effectively) a static class.
A public constructor implies that the class has instance methods - classes that don't shouldn't advertise otherwise.
If you have a class that only has shared methods, why do you need to create an instance of it?
An example of a class with only shared methods, is the System.Math class. It has a private constructor, as it adds no benefit (and it makes no sense) for it to be createable.
Source: http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/8addbc70-f720-4d0b-85ce-2bdf52e32f77
The question is why should I make it private, but why should stay public. Always grant the minimum access it is required.
Sealed is not the same as Static. A static class means that you cannot create an instance of a class with the new keyword. A sealed class means that you cannot create a class which inherits from it.
A class with all static method does never need a constructor as it is not instantiated with a new keyword. So you need no public constructor.
精彩评论