我知道在 C# 中我们不能覆盖非虚拟字段和方法,但我有以下情况:
Class Base
{
public static int a {get;set;}
public static void b()
{
// it uses a
}
public static void c()
{
// it uses a
}
public static string d {get {return a.ToString();}}
}
Class MyClass :Base
{
//...
}
现在在我的类 MyClass
中,我想覆盖所有 Base class
方法和属性开始使用被覆盖的属性的属性 a
我实现了,考虑到我无权更改 Base class
有什么办法可以做到这一点,即使我不得不 re-implement该属性的 getter 方法?
最佳答案
这是一个静态属性,因此以 Base.a
的形式使用。无论您做什么,调用代码仍将解析为 Base
类,然后解析为它的静态属性 a
。
例如
//old calling code
Base.a = 7; // does not create an instance
Console.WriteLine(Base.a);
class MyClass :Base
{
public static string a {get; set;}
}
//new calling code
MyClass.a = "some string"; // uses whatever a you defined in MyClass
Console.WriteLine(MyClass.a);
关于c# - 覆盖非虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20052159/