Static Class in C#

Adapted from:

http://blog.csdn.net/thy822/article/details/5111465

静态类只用于包含静态成员的类型,不能被实例化,我们可以直接使用它的属性与方法,静态类最大的特点就是共享。静态类的特性是防止继承,防止外部来NEW。它相当于一个sealed abstract类。

http://msdn.microsoft.com/zh-cn/library/79b3xss3(VS.80).aspx

静态类和静态类成员(C# 编程指南)
静态类和类成员用于创建无需创建类的实例就能够访问的数据和函数。静态类成员可用于分离独立于任何对象标识的数据和行为:无论对象发生什么更改,这些数据和函数都不会随之变化。当类中没有依赖对象标识的数据或行为时,就可以使用静态类。

静态类
类可以声明为 static 的,以指示它仅包含静态成员。不能使用 new 关键字创建静态类的实例。静态类在加载包含该类的程序或命名空间时由 .NET Framework 公共语言运行库 (CLR) 自动加载。

使用静态类来包含不与特定对象关联的方法。例如,创建一组不操作实例数据并且不与代码中的特定对象关联的方法是很常见的要求。您应该使用静态类来包含那些方法。

静态类的主要功能如下:

它们仅包含静态成员。

它们不能被实例化。

它们是密封的。

它们不能包含实例构造函数(C# 编程指南)。

因此创建静态类与创建仅包含静态成员和私有构造函数的类大致一样。私有构造函数阻止类被实例化。

使用静态类的优点在于,编译器能够执行检查以确保不致偶然地添加实例成员。编译器将保证不会创建此类的实利。

静态类是密封的,因此不可被继承。静态类不能包含构造函数,但仍可声明静态构造函数以分配初始值或设置某个静态状态。有关更多信息,请参见静态构造函数(C# 编程指南)。

何时使用静态类
假设有一个类 CompanyInfo,它包含用于获取有关公司名称和地址信息的下列方法。

view plaincopy to clipboardprint?C#   class CompanyInfo   {       public string GetCompanyName() { return "CompanyName"; }       public string GetCompanyAddress() { return "CompanyAddress"; }       //...   }  C#
class CompanyInfo
{
    public string GetCompanyName() { return "CompanyName"; }
    public string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}
不需要将这些方法附加到该类的具体实例。因此,您可以将它声明为静态类,而不是创建此类的不必要实例,如下所示:

view plaincopy to clipboardprint?C#   static class CompanyInfo   {       public static string GetCompanyName() { return "CompanyName"; }       public static string GetCompanyAddress() { return "CompanyAddress"; }       //...   }  C#
static class CompanyInfo
{
    public static string GetCompanyName() { return "CompanyName"; }
    public static string GetCompanyAddress() { return "CompanyAddress"; }
    //...
}
使用静态类作为不与特定对象关联的方法的组织单元。此外,静态类能够使您的实现更简单、迅速,因为您不必创建对象就能调用其方法。以一种有意义的方式组织类内部的方法(例如 System 命名空间中的 Math 类的方法)是很有用的。

静态成员
即使没有创建类的实例,也可以调用该类中的静态方法、字段、属性或事件。如果创建了该类的任何实例,不能使用实例来访问静态成员。只存在静态字段和事件的一个副本,静态方法和属性只能访问静态字段和静态事件。静态成员通常用于表示不会随对象状态而变化的数据或计算;例如,数学库可能包含用于计算正弦和余弦的静态方法。

在成员的返回类型之前使用 static 关键字来声明静态类成员,例如:

view plaincopy to clipboardprint?C#   public class Automobile   {       public static int NumberOfWheels = 4;       public static int SizeOfGasTank       {           get          {               return 15;           }       }       public static void Drive() { }       public static event EventType RunOutOfGas;       //other non-static fields and properties...   }  C#
public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    public static event EventType RunOutOfGas;
    //other non-static fields and properties...
}
静态成员在第一次被访问之前并且在任何静态构造函数(如调用的话)之前初始化。若要访问静态类成员,应使用类名而不是变量名来指定该成员的位置。例如:

view plaincopy to clipboardprint?C#   Automobile.Drive();   int i = Automobile.NumberOfWheels;  C#
Automobile.Drive();
int i = Automobile.NumberOfWheels;
示例
下面是一个静态类的示例,

using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Runtime;

namespace TruckTracker
{
    public static class WorkflowFactory
    {
        // Singleton instance of the workflow runtime
        private static WorkflowRuntime _workflowRuntime = null;

        // Lock (sync) object
        private static object _syncRoot = new object();

        // Factory method
        public static WorkflowRuntime GetWorkflowRuntime()
        {
            // Lock execution thread in case of multi-threaded
            // (concurrent) access.
            lock (_syncRoot)
            {
                // Check for startup condition
                if (null == _workflowRuntime)
                {
                    // Provide for shutdown
                    AppDomain.CurrentDomain.ProcessExit += new EventHandler(StopWorkflowRuntime);
                    AppDomain.CurrentDomain.DomainUnload += new EventHandler(StopWorkflowRuntime);

                    // Not started, so create instance
                    _workflowRuntime = new WorkflowRuntime();

                    // Start the runtime
                    _workflowRuntime.StartRuntime();
                } // if

                // Return singleton instance
                return _workflowRuntime;
            } // lock
        }

        // Shutdown method
        static void StopWorkflowRuntime(object sender, EventArgs e)
        {
            if (_workflowRuntime != null)
            {
                if (_workflowRuntime.IsStarted)
                {
                    try
                    {
                        // Stop the runtime
                        _workflowRuntime.StopRuntime();
                    }
                    catch (ObjectDisposedException)
                    {
                        // Already disposed of, so ignore...
                    } // catch
                } // if
            } // if
        }
    }
}

原文地址:https://www.cnblogs.com/simonhaninmelbourne/p/2228727.html