c# attribute over main 属性

标签 c# attributes console.writeline

有人问我如何打印

line no 1
line no 2
line no 3

不改变读取的主要方法

static void Main(string[] args)
{
    Console.WriteLine("line no 2");
}

现在一种方法是为控制台应用程序设置多个入口点。但是我尝试了另一种方法如下:

class Program
{
    [Some]
    static void Main(string[] args)
    {
        Console.WriteLine("line no 2");
    }
}
class SomeAttribute : Attribute
{
    public SomeAttribute()
    {
        Console.WriteLine("line no 1");
    }
    ~SomeAttribute()
    {
        Console.WriteLine("line no 3");
    }
}

当我在每个 WriteLine 上应用断点时,我能够看到该方法有效,但是,控制台上没有反射(reflect)出来。

只是好奇。

最佳答案

您的问题可以分解为钩子(Hook)的搜索,这些钩子(Hook)在控制台应用程序的 Main 方法执行之前和之后触发。

  • 第一个钩子(Hook)是一个Program静态构造器,它是guaranteeProgram 类中执行 before Main 方法。

  • 第二个是事件 ProcessExit AppDomain“在默认应用程序域的父进程退出时发生”。您可以使用静态构造函数来订阅此事件。


class Program
{
    static Program()
    {
        Console.WriteLine("line no 1");

        AppDomain.CurrentDomain.ProcessExit += 
                                          (s, a) => Console.WriteLine("line no 3");
    }

    static void Main(string[] args)
    {
        Console.WriteLine("line no 2");
    }
}

打印:

line no 1
line no 2
line no 3

下一部分会很长。我将尝试在您的问题中解释 SomeAttribute 的问题。

首先,考虑这个 StackOverflow 问题以准确知道 when custom attributes constructors are executed .这并不像乍一看那样简单。

我们已经知道,自定义属性的构造函数只会在您通过反射访问它时执行。所以在你的例子中,简单的程序执行不会触发属性构造函数。但是,当您将 SomeAttribute 应用于 Main 方法时,为什么会命中断点?事实证明,visual studio 使用反射来找出 main 方法并将调试器附加到您的应用程序。但是此时没有控制台窗口。所以声明 Console.WriteLine 是无用的并且会产生效果。此外,它似乎阻止了所有下一个语句到控制台输出。

因此接下来的代码将产生不同的结果,具体取决于您是否使用 VS 调试器运行它:

class Program
{
    [MyAttribute]
    static void Main()
    {

    }
}

class MyAttribute : Attribute
{
    public MyAttribute()
    {
        MessageBox.Show("MyAttribute ctor");
    } 
}

如果您在没有调试器的情况下运行它(VS 默认配置中的 Ctrl + F5),您会看到该程序终止并且没有窗口出现。当您使用调试器 (F5) 执行它时,您会看到

enter image description here

VS 旁边没有控制台窗口,只有 win 表单图标: enter image description here

正如我之前所描述的,当您尝试在没有控制台的情况下写入控制台时,所有其他对 Console.WriteLine 的调用都不会影响您的控制台应用程序。这就是为什么您可以看到任何控制台消息,即使您在构造函数中执行断点也是如此。

关于c# attribute over main 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15987026/

相关文章:

c# - Wp8 - 从应用程序重定向并返回时,EventHandler 为 null

c# - 如何在 C# 代码中使用 python NLP POS 标记器?

c# - System.Runtime.InteropServices.GuidAttribute 是否用于除 COM 互操作之外的任何内容

javascript - jquery attr 选择器不选择属性的整个值

C# Console.WriteLine 不是从方法调用的

c# - 在 Linq Select 中创建元组

带有 ref 参数的 c# 静态方法 - 一个好主意?

javascript - 使用 html 自定义属性值将类名添加到 html 元素

c# - 如何在 Console.WriteLine() 语句中将数字转换为字母