Svi*_*ish 8 c# inheritance properties accessor
在基类中我有这个属性:
public virtual string Text
{
get { return text; }
}
Run Code Online (Sandbox Code Playgroud)
我想覆盖它并返回一个不同的文本,但我也希望能够设置文本,所以我这样做:
public override string Text
{
get { return differentText; }
set { differentText = value; }
}
Run Code Online (Sandbox Code Playgroud)
然而,这不起作用.我得到一个红色的波浪形,set说我无法覆盖,因为它没有设置访问器.为什么这是个问题?我该怎么办?
public virtual string Text
{
get { return text; }
protected set {}
}
Run Code Online (Sandbox Code Playgroud)
像这样更改基类属性,您正在尝试覆盖不存在的set方法
在第二个代码块中,您正在创建一个公共集方法,但声明中的"override"一词使编译器在基类中查找具有相同签名的方法.由于找不到该方法,因此不允许您创建集合.
正如ArsenMkrt所说,您可以更改基本声明以包含受保护的集合.这将允许您覆盖它,但由于您仍然无法更改签名,因此您无法在子类中将此方法提升为public,因此您发布的代码仍然无效.
相反,您需要向基类添加一个公共虚拟集方法,该方法不执行任何操作(如果您尝试调用它,甚至会抛出异常),但这违背了该类用户期望该行为的内容.所以,如果你这样做(我不会推荐它),请确保它有很好的文档记录,用户不能错过它:
///<summary>
///Get the Text value of the object
///NOTE: Setting the value is not supported by this class but may be supported by child classes
///</summary>
public virtual string Text
{
get { return text; }
set { }
}
//using the class
BaseClass.Text = "Wibble";
if (BaseClass.Text == "Wibble")
{
//Won't get here (unless the default value is "Wibble")
}
Run Code Online (Sandbox Code Playgroud)
否则将该集声明为子类中的单独方法:
public override string Text
{
get { return differentText; }
}
public void SetText(string value)
{
differentText = value;
}
Run Code Online (Sandbox Code Playgroud)