gpt4 book ai didi

c# - 派生类中属性的可见性 (C#)

转载 作者:行者123 更新时间:2023-11-30 21:10:48 28 4
gpt4 key购买 nike

我一直在尝试将正确的 OOP 原则应用于我的项目。我有一个名为 DocumentSection 的抽象类,以及从它派生的几个类(DocumentSectionView、DocumentSectionText 等)。同样,我有一个抽象类 (DocAction),其中有几个派生自它的类(DocumentActionReplaceByTag、DocumentSectionAppend 等)。每个 DocumentSection 中都有一个 DocumentAction。

我对所有这些继承业务的理解是,通过指定“DocumentAction”,这将允许将任何派生类放在它的位置,并且基类的任何属性/方法也将可用正如我实例化的具体类中指定的那样。所以在下面的示例中,我希望能够看到 PerformAction 方法(暂时不考虑 virtual/override 关键字)。它是可用的。

但是,因为我使用了 v.DocAction = new DocumentActionReplaceByTag();,所以我还希望我的 ReplaceActionFindText 属性可见。

显然我在某处弄错了 - 任何评论表示赞赏。

class Program
{
static void Main(string[] args)
{
DocumentSectionView v = new DocumentSectionView();
v.DocAction = new DocumentActionReplaceByTag();

// would like to go:
//v.DocAction.ReplaceActionFindText...

Console.ReadLine();
}
}
public abstract class DocumentSection
{
public abstract string GetContent();
public DocumentAction DocAction { get; set; }
}
public class DocumentSectionView : DocumentSection
{
public string ViewPath { get; set; }
public dynamic ViewModel { get; set; }

public override string GetContent()
{
return "test";
}
}
public abstract class DocumentAction
{
void PerformAction(StringBuilder sb, string content);
}
public class DocumentActionReplaceByTag : DocumentAction
{
public string ReplaceActionFindText { get; set; }
public void PerformAction(StringBuilder sb, string content)
{
sb.Replace(ReplaceActionFindText, content);
}
}

编辑:我已将答案标记为正确,但我想我会为以后遇到此问题的人添加我对此事的进一步思考的成果:

a) 如前所述,我的意图大体上是正确的,但我的方法是错误的。从 Main 方法设置“Action”的属性不正确。在所有情况下,DocumentActionReplaceByTag 都需要 FindText,所以我将它放在构造函数中:

    public DocumentActionReplaceByTag(string replaceActionFindText)
{
this.ReplaceActionFindText = replaceActionFindText;
}

从那时起,具有 0 个参数的构造函数将正确地失败,并防止执行操作但未指定 findtext 的情况。

b) 多态性现在工作正常,因为我的额外属性 findtext 已被填充,并且无论操作类型如何,运行 PerformAction 都将正确运行。

最佳答案

因为您将派生类分配给具有基类类型的属性,所以只有基类的方法和属性可用。这是有道理的,因为您可以分配派生自基类的类的任何实例 - 因此在此上下文中不能使用任何派生方法。

这是 OOP 原则之一 - 您的派生类实例可以用作基类的实例(但反之则不行)

编辑:

详细说明@sll 提出的转换为特定派生类类型的解决方案:不要这样做!这是一种解决方法,但不符合整体设计的利益。

如果您必须转换为派生类型,那么您就违反了 Liskov substitution principle这意味着任何派生类型都应该可以用来代替基类型——如果您需要特定的强制转换,情况显然不是这样。

重新考虑您的设计 - 您是否真的需要具有基类类型的属性?如果需要,目前仅在一个特定派生类型中的方法最好也位于基类型中吗?

关于c# - 派生类中属性的可见性 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8282291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com