【问题标题】:How do i print any value after Main() method gets called?调用 Main() 方法后如何打印任何值?
【发布时间】:2011-10-22 23:18:51
【问题描述】:

我有以下代码,我在使用静态构造函数调用 Main() 方法之前打印值。如何在 Main() 返回后打印另一个值,不修改 Main() 方法

我想要这样的输出:

1st 
2nd 
3rd

我使用的“基础”代码:

class Myclass
{        
    static void Main(string[] args)
    {
        Console.WriteLine("2nd");
    }              
}  

我在 Myclass 中添加了一个静态构造函数来显示“1st”

class Myclass
{     
static Myclass() { Console.WriteLine("1st"); }   //it will print 1st 
    static void Main(string[] args)
    {
        Console.WriteLine("2nd"); // it will print 2nd
    }              
}

现在我需要做的是打印第三个而不修改Main() 方法。如果可能的话,我该怎么做?

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    你不能在 C# 中。在其他语言(例如 C++)中,可以在静态或全局对象的析构函数中执行此操作,但 C# 中的终结器是不确定的。如果在进程结束之前对象没有被垃圾回收,它们甚至可能根本不会被调用。

    【讨论】:

    • 即便如此,主要方法是静态的——没有调用对象析构函数。因此,这里没有任何作用 - 仅当 appdomain 卸载时才卸载该类。
    【解决方案2】:

    添加另一个具有适合作为程序入口点的静态Main 的类。在这个电话Myclass.Main:

    class MyOtherClass {
      static void Main(string[] args) {
        Console.WriteLine("1st");
        Myclass.Main(args);
        Console.WriteLine("3rd");
      }
    }
    

    然后更改构建选项以选择MyOtherClass 作为程序入口点。在 VS 中,这是在 Project Properties | 中完成的。应用 |启动对象。在命令行中使用 `csc.exe 的 /main:typename 选项。

    【讨论】:

    • +1 可能是最好的结果。给定参数在技术上也是合法的 - 重定向主方法是项目设置(入口点)的更改,而不是主方法本身,因此它保持在所要求的参数范围内。
    • @Ashish:只能覆盖虚拟方法; Main 是静态的,因此不能是虚拟的,因此不能被覆盖。
    【解决方案3】:

    您可以附加几个事件来捕获应用程序的退出事件:

    .NET Console Application Exit Event

    但我想知道你在这里想要达到什么目的?你确定你不能改变你的 Main 方法吗?如果不是,为什么?

    你能不能把 Main 的方法体分离成另一个方法,让你的 Main 看起来像这样:

    class Myclass
    {     
    static Myclass() 
        static void Main(string[] args)
        {
            Console.WriteLine("1st");
            Process(args);
            Console.WriteLine("3rd");
        }  
    
        static void Process(string[] args) {
            Console.WriteLine("2nd"); // it will print 2nd
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用静态构造函数继续您的相同想法,您可以使用 AppDomain.ProcessExit 事件使 Main() 保持不变。

      class Myclass
          {
              // will print 1st also sets up Event Handler
              static Myclass()
              {
                  Console.WriteLine("1st");
                  AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
              }
      
              static void Main(string[] args)
              {
                  Console.WriteLine("2nd"); // it will print 2nd
              }
      
              static void CurrentDomain_ProcessExit(object sender, EventArgs e)
              {
                  Console.WriteLine("3rd");
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 2014-10-29
        • 2021-12-21
        • 2017-02-13
        • 1970-01-01
        • 1970-01-01
        • 2018-05-01
        相关资源
        最近更新 更多