C#Overide Variable

时间:2016-10-15 20:18:38

标签: c# inheritance override parent-child superclass

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

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

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

class bar:foo;
{

public bar()
{

override nameOfInt = 0x00;

}
}

2 个答案:

答案 0 :(得分:1)

如果我们想要force实施,那么interface就是最佳选择。它告诉继承的对象rules (methods, properties...) must be implemented

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

来到你的代码:

property - nameOfInt名为abstract,并且未包含在abstract类中 - 根据规范,这是错误的。

这就是你应该如何解决的问题:

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

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

        set
        {
            throw new NotImplementedException();
        }
    }
}

答案 1 :(得分:-1)

我们不能谈论覆盖继承中的一个属性,我想你谈论方法覆盖,在这种情况下,你可以通过使父类抽象或使类继承自包含方法的接口来强制它覆盖。

相关问题