我可以覆盖 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
的派生类定义会隐藏它的 Base 版本.是否可以像方法一样覆盖 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?
推荐答案
需要使用virtual
关键字
abstract class Base
{
// use virtual keyword
public virtual int x
{
get { throw new NotImplementedException(); }
}
}
或者定义一个抽象属性:
or define an abstract property:
abstract class Base
{
// use abstract keyword
public abstract int x { get; }
}
并在孩子中使用 override
关键字:
and use override
keyword when in the child:
abstract class Derived : Base
{
// use override keyword
public override int x { get { ... } }
}
如果您不打算覆盖,您可以在方法上使用 new
关键字来隐藏父级的定义.
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 new keyword
public new int x { get { ... } }
}
这篇关于我可以覆盖 c# 中的属性吗?如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文