5

C# 9.0新特性——程序集的初始器

 3 years ago
source link: https://www.cnblogs.com/TianFang/p/14165865.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C# 9.0提供了一个比较给力的功能——程序集的初始器。它可以使得系统在加载程序集的时候,首先调用一个指定的函数。功能上类似于静态构造函数。只不过静态构造函数是作用于类的,程序集初始化函数则作用于整个程序集。

使用方法比较简单,通过ModuleInitializerAttribute标记程序集中的一个函数即可。

    [ModuleInitializer]
    internal static void Initializer()
    {
        Console.WriteLine("hello world");
    }

当然,这个函数也是有些限制的。

  1. 该方法必须使静态的、无参的、返回值为void的函数。
  2. 该方法不能是泛型或者包含在泛型类型里
  3. 该方法必须是可从其所在模块里访问的。也就是说,方法的有效访问符必须是internal或者public,不能是局部方法。

如果有多个函数被ModuleInitializerAttribute标记,则这些函会被依次调用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK