我在课堂上收到警告信息,例如
在类声明中添加
Protected constructor or the
static`关键字
在我尝试了两种方法后,错误消失了。
static
没有constructor
public static class Program {
}
static
非protected
类
public class Program
{
protected Program() { }
}
那么我的上述解决方案中提到的Static Class与Protected Constructor有什么区别?哪一个最好用?
答案 0 :(得分:4)
static
类不需要实例来访问其成员。 static
类不能拥有实例成员(例如,静态类上不允许public int MyNumber;
,因为静态类上只允许使用静态成员)。但是,实例和静态成员都允许在非静态类上使用。具有protected
构造函数的类只能拥有自己创建的实例或从中继承的实例。
public class Program
{
protected Program()
{
// Do something.
}
public static Program Create()
{
// 100% Allowed.
return new Program();
}
public void DoSomething()
{
}
}
public static class AnotherClass
{
public static Program CreateProgram()
{
// Not allowed since it's protected.
return new Program();
}
}
public class SubProgram : Program
{
public static Program Create()
{
// Not allowed , because SubProgram has not been defined in the scope of Program class, we can not instantiate base class which has having protected or private constructor outside the scope of base class.
return new Program();
}
}
Program.Create(); // Can be called since Create is a static function.
Program.DoSomething() // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething(); // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram(); // Can't be called since Program's constructor is protected.
SubProgram.Create(); // Can be called since SubProgram inherits from Program.
至于性能,这种区别与性能无关。
答案 1 :(得分:2)
你可能只有类中的静态成员,代码分析器假定你的意图是不能创建类的实例,所以它要求你让类静态
public static class Program {
//...static members
}
或放置受保护/私有构造函数
public class Program {
protected Program { //OR private
}
//...static members
}
防止该类的实例被初始化。
静态类与非静态类基本相同,但有一个区别:静态类无法实例化。
参考Static Classes and Static Class Members (C# Programming Guide)
受保护的构造函数意味着只有派生类才能调用构造函数
和私有构造函数不允许任何其他类使用私有构造函数
初始化类答案 2 :(得分:1)
在实例化类类型时调用静态构造函数。在创建类的实例时调用受保护的构造函数。受保护的部分意味着只有继承该类的类才能调用它。
答案 3 :(得分:1)
静态构造函数:在实例化类类型时调用一次,并用于初始化静态成员。不创建类的实例。
受保护的构造函数:只能由类或继承它的类调用的构造函数。
最佳实践是,如果只希望继承的类能够创建类的实例,则应该有一个静态构造函数来初始化静态成员和受保护的构造函数。你可以两个都有。
public class MyClass
{
static readonly long _someStaticMember;
private bool _param;
static MyClass()
{
//Do Some Logic
_someStaticMember = SomeValueCalculated;
}
protected MyClass(bool param)
{
_param = param;
}
}
public class ChildClass: MyClass
{
public ChildClass(bool param) : base(param);
}
public class NotChildClass
{
public MyClass someObject = new MyClass(true); //Will Fail
}