惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
爱范儿
爱范儿
D
Docker
I
InfoQ
Microsoft Security Blog
Microsoft Security Blog
G
Google Developers Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tailwind CSS Blog
D
DataBreaches.Net
月光博客
月光博客
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Visual Studio Blog
MyScale Blog
MyScale Blog
B
Blog
阮一峰的网络日志
阮一峰的网络日志
L
LangChain Blog
Recent Announcements
Recent Announcements
Microsoft Azure Blog
Microsoft Azure Blog
WordPress大学
WordPress大学

博客园 - kings

项目团队成长日志--聆听客户声音,沟通无所不在 TOAD使用筆記 使电脑鼠标右键相应快的办法 非常好用的对日面试资料(转) IT技術者日本語面接(ぎじゅつしゃにほんごめんせつ)によく出(で)る100質問(しつもん) 获取应用程序路径 基元类型、值类型和引用类型(转自Q.yuhen) C# 2.0 - 泛型(Generics)(转自Q.yuhen) new 和 override 的区别(转自Q.yuhen) “多态”一个需要注意的问题(转自Q.yuhen) C# 方法参数 ref 详述(转自Q.yuhen) 浅析Family Show 2.0的动态换肤实现(转tonyqus) 浅析Family Show 2.0的子窗体实现(转tonyqus) webservice 遇到的小问题 泛型集合类型,赋予集合业务意义,增强集合的抽象使用(转-lizhe1985) WPF_Markup的几种写法 When I tab into a toolbar in WPF I can't tab out again? What can I do to change this tab behaviour? Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定之二:使用外部URL的XML文件)(转-大可山) Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定)(转-大可山)
再议 构造方法(转自Q.yuhen)
kings · 2007-09-23 · via 博客园 - kings

先看代码

  class Base
  {
    static Base()
    {
      Console.WriteLine("Base Static Constructor...");
    }

    public Base()
    {
      Console.WriteLine("Base Constructor...");
    }
  }

  class Class1 : Base
  {
    static Class1()
    {
      Console.WriteLine("Class1 Static Construcotor...");
    }

    public Class1()
    {
      Console.WriteLine("Class1 Constructor...");
    }

    public static int x;
  }

1. 执行

Class1.x = 13;

输出

Class1 Static Construcotor...

请注意!Base的静态构造方法并没有被执行。

2. 执行

new Class1();

输出

Class1 Static Construcotor...
Base Static Constructor...
Base Constructor...
Class1 Constructor...


请注意!

  • 静态构造方法:总是先执行继承类的静态构造,然后递归执行基类的静态构造。
  • 实例构造方法:总是先递归执行基类的实例构造方法,然后再执行继承类的构造方法。
关于静态构造方法执行的总结!
  • 在类型的第一个实例被创建之前,或者在类型的非继承字段或成员第一次被访问之前。
  • 在非继承静态字段被第一次访问之前。

记住这些差别是有必要的,否则可能造成数据没有被初始化等潜在错误!