静态属性问题 [英] Static property issue
本文介绍了静态属性问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
公共抽象类A
{
public static string f {get;组; }
}
公共类B:A {
静态B()
{
f =B;
}
}
公共类C:A
{
静态C()
{
f =C;
}
}
我的尝试:
C c = new C();
B b = new B();
结果是:
Cf是B
Bf是B
Af是B
我期望的是:
Cf是C
Bf是B
Af是NULL
如何使用静态属性实现这个?
解决方案
f
是static
:整个应用程序中都有一个。因为B
和C
都是从A派生的,所以它们共享相同的静态变量:你设置它的最后一个值无论你是通过B
或C
因此,您最近创建的实例定义了f
的值。
< blockquote>我找到了一个解决方案:
公共抽象类A
{
public static string f {get;组; }
}
公共舱B:A {
public < b> new static string f {get;组; }
静态B()
{
f =B;
}
}
公共舱C:A
{
public new 静态字符串f {get;组; }
静态C()
{
f =C;
}
}
对于该类及其派生子类的每个实例,静态成员都是相同的。
您找到的解决方案完全违背了静态属性。
为什么你觉得你需要这个属性是静态的,如果它对每个孩子班级都不一样?
编辑:示例实现。
public abstract class A
{
public 字符串 F { get ; 受保护 set ; }
}
public class B:A
{
public B()
{
F = B Class;
}
}
public class C: A
{
public C()
{
F = C Class;
}
}
希望这会有所帮助。
public abstract class A { public static string f { get; set; } } public class B : A { static B() { f = "B"; } } public class C : A { static C() { f = "C"; } }
What I have tried:
C c = new C(); B b = new B(); The result is: C.f is B B.f is B A.f is B what i expect is: C.f is C B.f is B A.f is NULL How to implement this using static property?
解决方案
f
isstatic
: there is one of it for the whole application. Because bothB
andC
are derived from A, they share the same static variable: the last value to you set it to will be the global value it has, regardless of whether you set it via an instance ofB
orC
So which ever instance you create most recently defines the value off
.
i found a solution of this:
public abstract class A
{
public static string f { get; set; }
}
public class B : A {
public new static string f { get; set; }
static B()
{
f = "B";
}
}
public class C : A
{
public new static string f { get; set; }
static C()
{
f = "C";
}
}
A static member is the same for every instance of the class and its derived children.
The solution you found completely defeats the point of having a static property.
Why do you think you need the property to be static, if it can be different for every child class?
Edit: example implementation.
public abstract class A { public string F { get; protected set; } } public class B : A { public B() { F = "B Class"; } } public class C : A { public C() { F = "C Class"; } }
Hope this helps.
这篇关于静态属性问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文