抽象类中的静态属性
有人能解释为什么静态属性为空吗?
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;
}
}
Could anybody explain why the static property is 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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为当您编写
Cc.P1
时,您实际上指的是Ca.P1
,因为那是它的声明位置(因为P1
是静态的) ,它不涉及多态性)。因此,不管表面如何,您的代码根本没有使用Cc
类,并且Cc
静态构造函数也不会执行。That because when you write
Cc.P1
, you're actually referring toCa.P1
because that's where it is declared (sinceP1
is static, it is not involved in polymorphism). So in spite of appearances, your code isn't using theCc
class at all, and theCc
static constructor is not executed.尝试以下操作:
如果 P1 不再为 null,这是因为访问静态 P1(在 Ca 中)不会导致 Cc 的静态实例触发(因此会在静态构造函数中分配值)。
Try the following:
If P1 is no longer null, it is because accessing the static P1 (in Ca) does not cause the static instance of Cc to fire (and therefore assign the value in the static constructor).
如果你真的想要这个值:
If you really want the value:
您在代码中滥用了一些 OOD 原则。例如,您在类中混合静态行为(巫术类似于单例设计模式)和多态性(您使用抽象基类但没有任何基类接口)。因为我们没有像“静态多态性”这样的东西,所以我们应该将这两个角色分开。
如果您更详细地描述您想要解决的问题,也许您会得到更准确的答案。
但无论如何你可以实现这样的东西:
You misuse some OOD principles in your code. For example, you mix in your classes static behavior (witch is something like Singleton design pattern) and polymorphism (you use abstract base class but without any base class interface). And because we have no such thing like "Static Polymorphism" we should separate this two roles.
If you describe in more details what problem are you trying to solve, maybe you receive more accurate answers.
But anyway you may implement something like this: