[英]Statics Properties in abstract classes
谁能解释为什么静态属性为null?
class Program
{
static void Main(string[] args)
{
string s = Cc.P1; // is null
}
}
public class Cc
: Ca
{
static Cc()
{
P1 = "Test";
}
}
public abstract class Ca
{
public static string P1
{
get;
protected set;
}
}
那是因为在编写Cc.P1
,实际上是在引用Ca.P1
因为它是在其中声明的(因为P1
是静态的,所以它不参与多态性)。 因此,尽管看起来很漂亮,但是您的代码根本没有使用Cc
类,并且Cc
静态构造函数也没有执行。
请尝试以下操作:
string s = Cc.P1; // is null
Cc c = new Cc();
s = Cc.P1; // is it still null
如果P1不再为空,那是因为访问静态P1(在Ca中)不会导致Cc的静态实例触发(并因此在静态构造函数中分配值)。
如果您确实想要该值:
new Cc(); // call the static constructor
string s = Cc.P1; // not null now
您在代码中误用了一些OOD原则。 例如,您在类中混合了静态行为(女巫类似于Singleton设计模式)和多态性(使用抽象基类,但没有任何基类接口)。 而且因为我们没有“静态多态性”之类的东西,所以我们应该将这两个角色分开。
如果您详细描述要解决的问题,也许您会得到更准确的答案。
但是无论如何,您都可以实现以下内容:
public class Cc : Ca
{
private Cc()
: base("Test")
{
//We may call protected setter here
}
private static Ca instance = new Cc();
public static Ca Instance
{
get { return instance; }
}
}
public abstract class Ca
{
protected Ca(string p1)
{
P1 = p1;
}
//You may use protected setter and call this setter in descendant constructor
public string P1
{
get;
private set;
}
}
static void Main(string[] args)
{
string s = Cc.Instance.P1; // is not null
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.