我可以重写c#中的属性吗?怎么用?
我有一个基本类:我可以重写c#中的属性吗?怎么用?,c#,inheritance,properties,polymorphism,overriding,C#,Inheritance,Properties,Polymorphism,Overriding,我有一个基本类: abstract class Base { public int x { get { throw new NotImplementedException(); } } } 以及以下后代: class Derived : Base { public int x { get { //Actual Implementaion } } } 当我编译时,我得到一个警告,说派生类的x定义将隐藏它的Base版本。是否可以重写类c方法中的属性?您需要
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; }
}
并在子项中使用覆盖关键字:
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 }
}
}
或
更改属性签名,如下所示:
基类
public virtual int x
{ get { /* throw here*/ } }
public override int x
{ get { /*overriden logic*/ } }
派生类
public virtual int x
{ get { /* throw here*/ } }
public override int x
{ get { /*overriden logic*/ } }
若不需要基类中的任何实现,只需使用抽象属性即可
基础:
public abstract int x { get; }
public override int x { ... }
派生:
public abstract int x { get; }
public override int x { ... }
我建议您使用abstract
属性,而不是在getter中显示NotImplemented异常,absact
修饰符将强制所有派生类实现此属性,这样您将得到编译时安全的解决方案
abstract class Base
{
public virtual int x
{
get { throw new NotImplementedException(); }
}
}
或
在这两种情况下,都必须在派生类中编写
public override int x
{
get { your code here... }
}
两者之间的区别在于,使用abstract可以强制派生类实现某些东西,而使用virtaul可以提供默认行为,派生程序可以按原样使用或更改。或者可以在基类上使用virtual,正如Jeffrey Zhao提到的那样。
abstract class Base
{
// use abstract keyword
public virtual int x
{
get { throw new NotImplementedException(); }
}
}