C# 覆盖变量

C# Overide Variable

我有一个很基本的问题,对大多数人来说可能是显而易见的:

这是在继承 class 时强制覆盖变量的最佳方法吗?

class foo
{
public abstract int nameOfInt{get; set; }
}

class bar:foo;
{

public bar()
{

override nameOfInt = 0x00;

}
}

如果我们想要 force 实施,那么 interface 是可行的方法。它告诉继承对象 rules (methods, properties...) must be implemented

abstract class 的情况下,我们可以给出行为应该如何的基本定义,但我们不能从 abstract 实例化。

来到你的代码:

property - nameOfInt 被命名为 abstract 并且它不包含在 abstract class 中 - 根据规范这是错误的。

这是你应该如何处理的:

abstract class foo
{
    public abstract int nameOfInt { get; set; }
}

class bar : foo
{
    public override int nameOfInt
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }
}

我们不能谈论在继承中重写属性,我想你谈论的是方法重写,在那种情况下你可以通过使父 class 抽象或使 class 来强制它从包含要覆盖的方法的接口继承。