我可以覆盖在C#中的属性?怎么样? [英] Can I override a property in c#? How?
本文介绍了我可以覆盖在C#中的属性?怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个基类:
abstract class Base
{
public int x
{
get { throw new NotImplementedException(); }
}
}
和下面的后裔:
class Derived : Base
{
public int x
{
get { //Actual Implementaion }
}
}
当我编译我得到这样的警告说的派生类的定义X
是它会隐藏基地的版本。是否可以覆盖在C#中的属性,如方法?
When I compile I get this warning saying Derived class's definition of x
is gonna hide Base's version of it. Is is possible to override properties in c# like methods?
推荐答案
您需要使用虚拟
关键字
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; }
}
和使用覆盖
关键字时,在孩子:
and use override
keyword when in the child:
abstract class Derived : Base
{
// use override keyword
public override int x { get { ... } }
}
如果你不打算重写,可以使用新
关键字上隐藏父的定义方法。
If you're NOT going to override, you can use new
keyword on the method to hide the parent's definition.
abstract class Derived : Base
{
// use override keyword
public new int x { get { ... } }
}
这篇关于我可以覆盖在C#中的属性?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文