我有以下代码,我在使用静态构造函数调用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()
方法的情况下打印第3个。如果可能的话,我该怎么做?
答案 0 :(得分:6)
继续使用静态构造函数,您可以使用保留Main()的AppDomain.ProcessExit事件不受影响。
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");
}
}
答案 1 :(得分:5)
您可以附加一些事件来捕获应用程序的退出事件:
.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
}
}
答案 2 :(得分:3)
你不能在C#中。在其他语言(如C ++)中,可以在静态或全局对象的析构函数中执行此操作,但C#中的终结符是非确定性的。如果在进程结束之前对象没有被垃圾收集,则甚至可能根本不会调用它们。
答案 3 :(得分:3)
添加另一个类,其中静态Main
适合作为程序入口点。在此致电Myclass.Main
:
class MyOtherClass {
static void Main(string[] args) {
Console.WriteLine("1st");
Myclass.Main(args);
Console.WriteLine("3rd");
}
}
然后更改构建选项以选择MyOtherClass
作为程序入口点。在VS中,这是在Project Properties |中完成的应用|启动对象。使用命令行使用{cls.exe。{/ p>的/main:typename
选项