【问题标题】:C# Overide Variable [closed]C# 覆盖变量
【发布时间】:2017-02-25 02:29:58
【问题描述】:

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

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

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

class bar:foo;
{

public bar()
{

override nameOfInt = 0x00;

}
}

【问题讨论】:

  • 这取决于您的要求。
  • 此时我唯一的要求是,当类 'foo' 被继承时,必须重写该变量。对不起,如果我遗漏了什么;我对此很陌生...
  • 你的代码语法错误
  • 然后将其抽象化,迫使具体的后代实现它。请注意,它不是变量,而是属性,因此您的 bar 示例将无法编译,因为它会覆盖属性并创建字段。

标签: c# inheritance overriding parent-child superclass


【解决方案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();
        }
    }
}

【讨论】:

【解决方案2】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-01-20
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 2018-09-27
  • 2021-08-24
  • 2020-09-30
相关资源
最近更新 更多