【发布时间】:2014-07-13 01:32:15
【问题描述】:
我很难在 C# 中实现一个在抽象基类中只有一个 getter 的属性,但是我需要在其中一个中引入一个 setter派生类。
更新:有关此问题的一般示例的简短说明,see this question。所选答案解释了为什么目前在 C# 中无法做到这一点,但是,在我看来,还没有提供令人满意的解决方案。
我的类图概览如下所示:
我的目标是 TextElementStatic 和 TextElementReferenceSource 这两个类应该有一个 Text 属性,其中包含 getter 和 setter,而类 TextElementReferenceTarget 应该有一个只有 getter 的 Text 属性。我在引用所有这些对象时经常使用 ITextElement,并且我需要确保 ITextElement 接口只有一个 getter。另外,基类TextElement实现了很多通用代码,所以所有的类都需要继承自该类。
我当前的代码如下所示:
接口:ITextElement
public interface ITextElement
{
string Text { get; }
}
接口:ITextElementUpdatable
public interface ITextElementUpdatable : ITextElement
{
new string Text { get; set; }
}
抽象类:TextElement (这是我的问题所在,如下所述)
public abstract class TextElement : ITextElement
{
// I want to mark this 'abstract', but that causes my problem
public virtual string Text
{
get
{
// NOTE: This should never be called
Debug.Fail("Called virtual Text getter that should never be called");
return default(string);
}
}
}
抽象类:TextElementUpdatable
public abstract class TextElementUpdatable : TextElement, ITextElementUpdatable
{
// Should have both a getter and a setter
public new virtual string Text { get; set; }
}
类:TextElementStatic
public class TextElementStatic : TextElementUpdatable
{
// Should have both a getter and a setter
// No Text property declaration
// Inherits Text property from TextElementUpdatable
}
类:TextElementReferenceSource
public class TextElementReferenceSource : TextElementUpdatable
{
// Should have both a getter and a setter
public override string Text
{
get { return _internalobject.Text; }
set { _internalobject.Text = value; }
}
}
类:TextElementReferenceTarget
public class TextElementReferenceTarget : TextElement
{
// Should ONLY have a getter
public override string Text
{
get { return _internalobject.Text; }
}
}
所以,我的问题是:我真的想在基类 TextElement 抽象中声明 Text 属性,因为它应该始终在派生类中实现(TextElementUpdatable、TextElementReferenceSource 和 TextElementReferenceTarget 都实现了这个属性)。但是,如果我尝试将属性转换为 public abstract string Text { get; },那么我会在 TextElementUpdatable 中收到一个错误,指定
TextElementUpdatable.Text hides the inherited property TextElement.Text
此外,如果我将 TextElementUpdatable 中的属性从 new 更改为 override,则错误消息将替换为:
Cannot override because TextElement.Text does not have an overridable set accessor
现在,我可以回到 TextElement 并将属性更改为 public virtual string Text { get; private set; } 并每天调用它,因为无论如何都不应该调用该方法(这基本上是我现在的解决方案) .但是,如果我或某人稍后创建另一个派生类,我想强制我/他们实现 Text-property,因此我宁愿将其标记为抽象而不是提供虚拟实现。
关于如何以正确的方式做到这一点的任何建议 - 即使它应该涉及大量重构?
我知道我可以把她的两个目标分开,提供一个继承的Text属性,只有一个getter,然后在ITextElementUpdatable接口中引入SetText()方法.但是,我想知道是否可以仅使用属性找到一个好的解决方案。
另一个类似的问题,但我无法使用任何答案:C# - What should I do when every inherited class needs getter from base class, but setter only for ONE inherited class
【问题讨论】:
-
+1 表示非常解释得很好且书面的问题。不幸的是,我认为我没有给你一个好的答案,在我看来你已经找到了最好的/唯一的解决方法。祝你好运!
-
this 有帮助吗?
-
@WilliamBarbosa 谢谢,我在研究期间没有找到那个。它看起来像同样的问题。不过,我对答案并不特别满意,因为这对我来说似乎太过分了。然后我宁愿使用
SetProperty()解决方案,因为我发现它更清洁 - 除非有人可以提供不同的答案..
标签: c# .net inheritance properties overriding