解析C#中的公有結構函數和靜態結構函數。本站提示廣大學習愛好者:(解析C#中的公有結構函數和靜態結構函數)文章只能為提供參考,不一定能成為您想要的結果。以下是解析C#中的公有結構函數和靜態結構函數正文
公有結構函數
公有結構函數是一種特別的實例結構函數。它平日用在只包括靜態成員的類中。假如類具有一個或多個公有結構函數而沒有公共結構函數,則其他類(除嵌套類外)沒法創立該類的實例。例如:
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = Math.E; //2.71828...
}
聲明空結構函數可阻攔主動生成默許結構函數。留意,假如您纰謬結構函數應用拜訪潤飾符,則在默許情形下它仍為公有結構函數。然則,平日顯式地應用 private 潤飾符來清晰地注解該類不克不及被實例化。
當沒有實例字段或實例辦法(如 Math 類)時或許當挪用辦法以取得類的實例時,公有結構函數可用於阻攔創立類的實例。假如類中的一切辦法都是靜態的,可斟酌使全部類成為靜態的。
上面是應用公有結構函數的類的示例。
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine("New count: {0}", Counter.currentCount);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
輸入:
New count: 101
留意,假如您撤消正文該示例中的以下語句,它將生成一個毛病,由於該結構函數受其掩護級其余限制而弗成拜訪:
// Counter aCounter = new Counter(); // Error
靜態結構函數
靜態結構函數用於初始化任何靜態數據,或用於履行僅需履行一次的特定操作。在創立第一個實例或援用任何靜態成員之前,將主動挪用靜態結構函數。
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;
}
}
靜態結構函數具有以下特色:
靜態結構函數的典范用處是:當類應用日記文件時,將應用這類結構函數向日記文件中寫入項。
靜態結構函數在為非托管代碼創立包裝類時也很有效,此時該結構函數可以挪用 LoadLibrary 辦法。
假如靜態結構函數激發異常,運轉時將不會再次挪用該結構函數,而且在法式運轉地點的運用法式域的生計期內,類型將堅持未初始化。
在此示例中,類 Bus 有一個靜態結構函數。創立 Bus 的第一個實例(bus1)時,將挪用該靜態結構函數來初始化該類。輸入示例驗證了即便創立 Bus 的兩個實例,該靜態結構函數也僅運轉一次,而且在實例結構函數運轉之前運轉。
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(71);
// Create a second bus.
Bus bus2 = new Bus(72);
// Send bus1 on its way.
bus1.Drive();
// Wait for bus2 to warm up.
System.Threading.Thread.Sleep(25);
// 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();
}
}
輸入:
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.