简体   繁体   English

C#抽象类实现

[英]C# Abstract Class Implementation

I am just starting to use abstract classes and would like to know if I am using them in the correct manner. 我刚刚开始使用抽象类,并且想知道我是否以正确的方式使用它们。 In my example I have a Windows Form application where Form1 is the main UI for the app. 在我的示例中,我有一个Windows Form应用程序,其中Form1是该应用程序的主UI。 Within Form1 I have a method which writes debug messages to a richtextbox. 在Form1中,我有一个将调试消息写入RichTextBox的方法。 I currently have a bunch of different classes which all have the same method in them to write message back to the main UI richtextbox. 我目前有很多不同的类,它们都具有相同的方法,可将消息写回到主UI richtextbox。 However, I was wondering if it would make sense to make this functionality part of an abstract class, an just have all of my other class inherit this functionality as shown below? 但是,我想知道将此功能作为抽象类的一部分是否有意义,让我的所有其他类都继承此功能,如下所示?

using System;
using System.Windows.Forms;

namespace abstractTest
{
    /// <summary>
    /// Main User Interface
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void RTBWriteLine(string message)
        {
            /* Print (append) message to the debug richtextbox */
            this.richTextBox1.AppendText(message + Environment.NewLine);

            /* Select the last entered message */
            this.richTextBox1.Select(richTextBox1.Text.Length, 0);

            /* Scroll to selected message */
            this.richTextBox1.ScrollToCaret();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Class1 c1 = new Class1(this);
            Class2 c2 = new Class2(this);
        }
    }

    public abstract class absTest
    {
        protected Form1 MainUI;

        public virtual void MainRTBWriteLine(string msg)
        {
            if (MainUI != null)
            {
                MainUI.RTBWriteLine(msg);
            }
        }
    }

    public class Class1 : absTest
    {
        public Class1(Form callingForm)
        {
            MainUI = callingForm as Form1;
            MainRTBWriteLine("This is Class1");
        }
    }

    public class Class2 : absTest
    {
        public Class2(Form callingForm)
        {
            MainUI = callingForm as Form1;
            MainRTBWriteLine("This is Class2");
        }
    }
}

Edit: My main goal is that I would to make DTBWriteLine(among many other methods that update the main UI is some way) to be available to all of my classes, but only have the code in one location. 编辑:我的主要目标是使DTBWriteLine(在更新主UI的许多其他方法中,某种方式)可用于我的所有类,但仅将代码放在一个位置。 Right now, I have the following method (among many others) duplicated in every class I've created: 现在,我在创建的每个类中都有以下方法(以及其他方法):

public virtual void MainRTBWriteLine(string msg)
{
    if (MainUI != null)
    {
        MainUI.RTBWriteLine(msg);
    }
}

If putting this in an abstract class isn't the best approach, what is? 如果将其放在抽象类中不是最佳方法,那是什么?

Yes, this scenario is a perfect example for using an abstract class. 是的,此方案是使用抽象类的完美示例。

When you have shared functionality in an inheritance tree. 在继承树中具有共享功能时。

An abstract class is one option in this situation, yes. 在这种情况下,抽象类是一种选择,是的。 An alternative (particularly if you want to reuse the same functionality from elsewhere) would be to create a utility method in a separate class. 另一种选择(尤其是如果您想从其他地方重用相同的功能)将是在单独的类中创建实用程序方法。 Inheritance is one way of achieving code reuse, but it's not always the best choice - consider the options carefully. 继承是实现代码重用的一种方法,但它并不总是最佳选择-请仔细考虑这些选项。

To me it seems that what you are after is a separate DebugLogger class whose only concern would be logging debug messages to the textbox. 在我看来,您所追求的是一个单独的DebugLogger类,它唯一关心的就是将调试消息记录到文本框中。

Then your other classes would just delegate debug logging to this one class rather than inheriting this additional functionality that has not much to do with their primary function. 然后,您的其他类将只将调试日志记录委派给该类,而不是继承与此主要功能没有多大关系的其他功能。

The point of an abstract class, according to the docs: 根据文档,抽象类的要点是:

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes 在类声明中使用abstract修饰符表示一个类仅打算作为其他类的基类

  • An abstract class cannot be instantiated. 抽象类无法实例化。
  • An abstract class may contain abstract methods and accessors. 抽象类可以包含抽象方法和访问器。
  • It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited. 无法使用密封修饰符修改抽象类,这意味着该类不能被继承。
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. 从抽象类派生的非抽象类必须包括所有继承的抽象方法和访问器的实际实现。

It makes sense and reflects the idea with abstract classes. 这是有意义的,并通过抽象类反映了这个想法。 In your examples it also provides you with a nice separation of concerns where your absTest implementations enables you to swap logging strategies at a single point if needed. 在您的示例中,它还为您提供了很好的关注点分离,其中的absTest实现使您可以根据需要在单个点交换日志记录策略。

Abstract classes are widely used to implement Template Method pattern. 抽象类被广泛用于实现Template Method模式。 Check C# implementation samples . 检查C#实现示例

I would add that in your example is not nessesary to use exactly abstract keyword. 我要补充一点,在您的示例中,不必完全使用abstract关键字。 absTest may be not abstract without any harm, and it would be fully functional in case of absTest(Form callingForm) constructor implementation. absTest可能不是abstract没有任何危害,并且在absTest(Form callingForm)构造函数实现的情况下它将完全起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM