【问题标题】:shared functionality between C# console appsC# 控制台应用程序之间的共享功能
【发布时间】:2009-10-21 19:51:02
【问题描述】:

我有两个控制台应用程序,查询和更新,它们共享一些功能。我想让这两个类继承自一个公共基类,但问题是,对于控制台应用程序,我必须有一个 static Main 函数。我目前拥有的是以下内容:

namespace Utils
{
    public class ConsoleBase
    {
        protected const int ERROR_EXIT_CODE = 1;
        protected static void printWarning(string msg) {...}
        public ConsoleBase(IEnumerable<string> args) { ... }
...

namespace Update
{
    class Update : ConsoleBase
    {
        private static ConsoleBase _consoleBase;
        public static void Main(string[] args) { ... }
...

namespace Query
{
    class Query : ConsoleBase
    {
        private static ConsoleBase _consoleBase;
        public static void Main(string[] args) { ... }
...

ConsoleBase 继承以及在每个派生类中将其实例作为static 变量对我来说似乎是一个设计问题。我这样做的原因是:

  1. 我可以在ConsoleBase 中定义protected static 方法,这些方法可供派生类中的其他static 方法访问。
  2. 我可以将命令行参数传递给ConsoleBase 的构造函数,做一些普通的事情,然后通过public 实例上的public 属性和方法再次访问派生类中的参数。李>

所以在派生类中,我在ConsoleBase 的实例上混合了对方法/属性的调用,例如

_consoleBase.UseDebugMode()

以及调用继承的静态方法和访问在ConsoleBase 中定义的继承常量,例如

printWarning(CONST_MSG_IN_BASE_CLASS);

我可以以某种方式清理它吗?从一个类继承并保留该基类的实例以供使用是不是很糟糕?

【问题讨论】:

    标签: c# inheritance console-application abstraction


    【解决方案1】:

    不要像这样混合使用静态方法和实例方法。

    考虑一下,将静态方法提供的职责分离到一个可以继承的不同类中。使非静态功能成为您在 Update 和 Query 中聚合和实例化的单独类。

    此外,如果 Update 和 Query 是 ConsoleBase 的衍生产品 - 为什么需要聚合实例?

    【讨论】:

    • 我喜欢将ConsoleBase 中的static 方法与实例方法分开的想法。现在,如果我能想出两个类的好名字...
    【解决方案2】:

    是的,您可以使用受保护的静态 main 定义基类,然后从继承类中的 Main 方法调用 BaseClass.Main(args)。

    这个语法更正确:

    public class BaseApp
    {
        public static Main(String[] args)
        {
            // TODO: ...
        }
    }
    
    public class App1 : BaseApp // Same for App2
    {
        // There is no need to keep a reference of the base class
        // if you are accessing static methods only
    
        public static Main(String[] args)
        {
            BaseApp.Main(args); // Access via class, not via instance
        }
    }
    

    【讨论】:

      【解决方案3】:

      我认为你不需要这样做。为什么不简单地使用命令行参数调用 ConsoleBase.Main() 函数?

      拥有基类的实例是一个设计问题。

      【讨论】:

      • 我希望将命令行参数存储为实例变量,因为它们要到运行时才能知道。如果我在ConsoleBase 中有一个static 主函数,我将无法访问该static 函数中的那些实例变量。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多