https://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.140).aspx

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only.

It is called automatically before the first instance is created or any static members are referenced.

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline; // Static constructor is called at most one time, before any
// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
}
}

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Example

In this example, class Bus has a static constructor.

When the first instance of Bus is created (bus1), the static constructor is invoked to initialize the class.

The sample output verifies that the static constructor runs only one time,

even though two instances of Bus are created, and that it runs before the instance constructor runs.

public class Bus
{
// Static variable used by all Bus instances.
// Represents the time the first bus of the day starts its route.
protected static readonly DateTime globalStartTime; // Property for the number of each bus.
protected int RouteNumber { get; set; } // Static constructor to initialize the static variable.
// It is invoked before the first instance constructor is run.
static Bus()
{
globalStartTime = DateTime.Now; // The following statement produces the first line of output,
// and the line occurs only once.
Console.WriteLine("Static constructor sets global start time to {0}",
globalStartTime.ToLongTimeString());
} // Instance constructor.
public Bus(int routeNum)
{
RouteNumber = routeNum;
Console.WriteLine("Bus #{0} is created.", RouteNumber);
} // Instance method.
public void Drive()
{
TimeSpan elapsedTime = DateTime.Now - globalStartTime; // For demonstration purposes we treat milliseconds as minutes to simulate
// actual bus times. Do not do this in your actual bus schedule program!
Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",
this.RouteNumber,
elapsedTime.TotalMilliseconds,
globalStartTime.ToShortTimeString());
}
} class TestBus
{
static void Main()
{
// The creation of this instance activates the static constructor.
Bus bus1 = new Bus(); // Create a second bus.
Bus bus2 = new Bus(); // Send bus1 on its way.
bus1.Drive(); // Wait for bus2 to warm up.
System.Threading.Thread.Sleep(); // Send bus2 on its way.
bus2.Drive(); // Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
/* Sample output:
Static constructor sets global start time to 3:57:08 PM.
Bus #71 is created.
Bus #72 is created.
71 is starting its route 6.00 minutes after global start time 3:57 PM.
72 is starting its route 31.00 minutes after global start time 3:57 PM.
*/

百度知道上的回答:

静态构造函数的作用:

初始化静态成员

比如有几个静态成员需要初始化
那你把初始化代码放到哪呢?

放到普通构造函数里,那肯定不行。因为静态成员没有创建实例就要可用。

专门建一个static public方法来初始化?这样用起来非常不方便,你需要在“第一次”使用静态成员前先调用这个方法。
如果你在使用静态成员前忘了调用该方法,会导致错误。
如果重复调用,又是冗繁操作。

所以静态构造函数就派上用场了。
它会在你第一次调用静态成员(或创建实例)的时候自动被调用

以上解释引自:http://zhidao.baidu.com/question/112464220.html

实例:

https://github.com/kerryjiang/SuperSocket.ClientEngine/blob/master/Common/ConnectAsyncExtension.Net40.cs

f:\codeforgitblit\supersocket.clientengine\common\connectasyncextension.net40.cs

using System.Net;
using System.Net.Sockets;
using System.Reflection; namespace SuperSocket.ClientEngine
{
public static partial class ConnectAsyncExtension
{
private static readonly MethodInfo m_ConnectMethod; private static bool m_OSSupportsIPv4; static ConnectAsyncExtension()
{
//.NET 4.0 has this method but Mono doesn't have
m_ConnectMethod = typeof(Socket).GetMethod("ConnectAsync", BindingFlags.Public | BindingFlags.Static); //Socket.OSSupportsIPv4 doesn't exist in Mono
var pro_OSSupportsIPv4 = typeof(Socket).GetProperty("OSSupportsIPv4", BindingFlags.Public | BindingFlags.Static); if (pro_OSSupportsIPv4 != null)
{
m_OSSupportsIPv4 = (bool)pro_OSSupportsIPv4.GetValue(null, new object[]);
}
else
{
m_OSSupportsIPv4 = true;
}
} public static void ConnectAsync(this EndPoint remoteEndPoint, ConnectedCallback callback, object state)
{
//Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, e);
//Don't use Socket.ConnectAsync directly because Mono hasn't implement this method
if (m_ConnectMethod != null)
m_ConnectMethod.Invoke(null,
new object[]
{
SocketType.Stream,
ProtocolType.Tcp,
CreateSocketAsyncEventArgs(remoteEndPoint, callback, state)
});
else
{
ConnectAsyncInternal(remoteEndPoint, callback, state);
}
} static partial void CreateAttempSocket(DnsConnectState connectState)
{
if (Socket.OSSupportsIPv6)
connectState.Socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); if (m_OSSupportsIPv4)
connectState.Socket4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
}
}

C#中的静态构造函数的更多相关文章

  1. C#中静态构造函数含义及使用

    static以前都接触过,可是最近才发现了还有静态类的写法,也可能是以前没太注意了,所以自己去研究了一下! 1.什么是构造函数: 1.1 例如:static  Class{} 1.2 使用静态函数的注 ...

  2. C#中静态构造函数

    静态构造函数用于初始化任何静态数据,或执行仅需执行一次的特定操作. 将在创建第一个实例或引用任何静态成员之前自动调用静态构造函数. 静态构造函数的属性 1. 静态构造函数不使用访问修饰符或不具有参数. ...

  3. C# 静态构造函数使用

    当我们想初始化一些静态变量的时候,就需要用到静态构造函数了.这个静态构造函数属于类,而不属于实例,就是说这个构造函数只会被执行一次,即:在创建第一个实例或引用任何静态成员之前,由.NET自动调用. 现 ...

  4. 深入了解C#中的静态变量和静态构造函数

    深入的剖析C#中静态变量和静态构造函数: 在日常的程序开发过程经常会使用到静态变量,众所周知,静态变量时常驻内存的变量,它的生命周期是从初始化开始一直到Application结束.但是,我们经常会忽略 ...

  5. MVC5中Model层开发数据注解 EF Code First Migrations数据库迁移 C# 常用对象的的修饰符 C# 静态构造函数 MSSQL2005数据库自动备份问题(到同一个局域网上的另一台电脑上) MVC 的HTTP请求

    MVC5中Model层开发数据注解   ASP.NET MVC5中Model层开发,使用的数据注解有三个作用: 数据映射(把Model层的类用EntityFramework映射成对应的表) 数据验证( ...

  6. 2.java中c#中statc 静态调用不同之处、c#的静态构造函数和java中的构造代码块、静态代码块

    1.java和c#静态成员调用的不同之处 static 表示静态的,也就是共享资源,它是在类加载的时候就创建了 java中   可以通过实例来调用,也可以通过类名.成员名来调用,但是一般最好使用类名. ...

  7. java类中,成员变量赋值第一个进行,其次是静态构造函数,再次是构造函数

    如题是结论,如果有人问你Java类的成员初始化顺序和初始化块知识就这样回答他.下面是代码: package com.test; public class TestClass{ // 成员变量赋值第一个 ...

  8. c#静态构造函数 与 构造函数 你是否还记得?

    构造函数这个概念,在我们刚开始学习编程语言的时候,就被老师一遍一遍的教着.亲,现在你还记得静态构造函数的适用场景吗?如果没有,那么我们一起来复习一下吧. 静态构造函数是在构造函数方法前面添加了stat ...

  9. 深入浅出C#中的静态与非静态

    C#语言静态类 vs 普通类  C#语言静态类与普通类的区别有以下几点: 1)C#语言静态类无法实例化而普通类可以: 2)C#语言静态类只能从System.Object基类继承:普通可以继承其它任何非 ...

随机推荐

  1. Excel 中如何快速统计一列中相同字符的个数(函数法)

    https://jingyan.baidu.com/article/6d704a132ea17328da51ca78.html 通过excel快速统计一列中相同字符的个数,如果很少,你可以一个一个数. ...

  2. 2015.10.11(js判断鼠标进入容器的方向)

    判断鼠标进入容器的方向 1.前几天在万圣节专题项目中用到了鼠标坐标page事件,随着鼠标背景图片移动形成有层次感的效果,但page事件在IE低版本不支持,所以还要做兼容.在研究page事件同时无意中想 ...

  3. EUI Scroller实现自定义图片轮播 组件ScrollView

    一 自定义组件如下 /** * 文 件 ScrollView.ts * 功 能: 滚动组件 * 内 容: 自定义组件,支持多张图片水平(垂直)切换滚动 * * Example: * 1. 从自定义组件 ...

  4. windows服务的默认启动类型和登录帐户

    转自:http://www.winhelponline.com/blog/windows-7-services-default-startup-type/ Service Name Startup T ...

  5. thymeleaf 学习笔记-基础篇(中文教程)

    (一)Thymeleaf 是个什么?      简单说, Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下 ...

  6. 170531、FormData 对象的使用

    通过FormData对象可以组装一组用 XMLHttpRequest发送请求的键/值对.它可以更灵活方便的发送表单数据,因为可以独立于表单使用.如果你把表单的编码类型设置为multipart/form ...

  7. Oracle Schema Objects——View

    Oracle Schema Objects Oracle视图View 普通视图.物化视图 视图(视图不包含数据,不是段对象,不占用空间,只是一个代码.) 作用: 简化SQL 为安全,不暴露表的名称 视 ...

  8. make linux test main attempt to index a nil value

    Lua: getting started http://www.lua.org/start.html#learning Building from source Lua is very easy to ...

  9. Python爬虫框架Scrapy实例(二)

    目标任务:使用Scrapy框架爬取新浪网导航页所有大类.小类.小类里的子链接.以及子链接页面的新闻内容,最后保存到本地. 大类小类如下图所示: 点击国内这个小类,进入页面后效果如下图(部分截图): 查 ...

  10. 两个提高工作效率的神器-Restlet Client和fe助手

    首先是要FQ,百度***或者直接下载蓝灯. 然后安装第一个WEB前端助手: