繁体   English   中英

我可以覆盖 c# 中的属性吗? 如何?

[英]Can I override a property in c#? How?

我有这个基类:

abstract class Base
{
  public int x
  {
    get { throw new NotImplementedException(); }
  }
}

以及以下后代:

class Derived : Base
{
  public int x
  {
    get { //Actual Implementaion }
  }
}

当我编译时,我收到这个警告说派生类的x定义将隐藏它的 Base 版本。 是否可以像方法一样覆盖 c# 中的属性?

您需要使用virtual关键字

abstract class Base
{
  // use virtual keyword
  public virtual int x
  {
    get { throw new NotImplementedException(); }
  }
}

或定义一个抽象属性:

abstract class Base
{
  // use abstract keyword
  public abstract int x { get; }
}

并在孩子中使用override关键字:

abstract class Derived : Base
{
  // use override keyword
  public override int x { get { ... } }
}

如果您不打算覆盖,则可以在方法上使用new关键字来隐藏父级的定义。

abstract class Derived : Base
{
  // use new keyword
  public new int x { get { ... } }
}

使基本属性抽象并覆盖或在派生类中使用 new 关键字。

abstract class Base
{
  public abstract int x { get; }
}

class Derived : Base
{
  public override int x
  {
    get { //Actual Implementaion }
  }
}

或者

abstract class Base
{
  public int x { get; }
}

class Derived : Base
{
  public new int x
  {
    get { //Actual Implementaion }
  }
}

更改属性签名如下所示:

基类

public virtual int x 
{ get { /* throw here*/ } }

派生类

public override int x 
{ get { /*overriden logic*/ } }

如果您不需要基类中的任何实现,只需使用抽象属性。

根据:

public abstract int x { get; }

衍生的:

public override int x { ... }

我建议您使用abstract属性而不是在 getter 中抛出 NotImplemented 异常, abstact修饰符将强制所有派生类实现此属性,因此您最终会得到编译时安全的解决方案。

abstract class Base
{

  public virtual int x
  {
    get { throw new NotImplementedException(); }
  }
}

或者

abstract class Base
{
  // use abstract keyword
  public abstract int x
  {
    get;
  }
}

在这两种情况下,您都必须在派生类中编写

public override int x
  {
    get { your code here... }
  }

两者之间的区别在于,使用 abstract 可以强制派生类实现某些东西,而使用 virtaul 可以提供派生者可以按原样使用或更改的默认行为。

abstract class Base 
{ 
  // use abstract keyword 
  public virtual int x 
  { 
    get { throw new NotImplementedException(); } 
  } 
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM