如果您不喜歡允許使用靜態類來實例化它,那麼您可以使用靜態類,它的最佳示例是Math
類,並且如果您想要有單個實例,則可以使用單例。 MSDN示例:
public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = System.Double.Parse(temperatureCelsius);
// Convert Celsius to Fahrenheit.
double fahrenheit = (celsius * 9/5) + 32;
return fahrenheit;
}
public static double FahrenheitToCelsius(string temperatureFahrenheit)
{
// Convert argument to double for calculations.
double fahrenheit = System.Double.Parse(temperatureFahrenheit);
// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5/9;
return celsius;
}
}
class TestTemperatureConverter
{
static void Main()
{
System.Console.WriteLine("Please select the convertor direction");
System.Console.WriteLine("1. From Celsius to Fahrenheit.");
System.Console.WriteLine("2. From Fahrenheit to Celsius.");
System.Console.Write(":");
string selection = System.Console.ReadLine();
double F, C = 0;
switch (selection)
{
case "1":
System.Console.Write("Please enter the Celsius temperature: ");
F = TemperatureConverter.CelsiusToFahrenheit(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;
case "2":
System.Console.Write("Please enter the Fahrenheit temperature: ");
C = TemperatureConverter.FahrenheitToCelsius(System.Console.ReadLine());
System.Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;
default:
System.Console.WriteLine("Please select a convertor.");
break;
}
}
}
和創建類單做到這一點:
public sealed class MyClass
{
MyClass()
{
}
public static MyClass Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly MyClass instance = new MyClass();
}
}
對我幫助很大!但它有過度使用靜態類的有什麼區別,如如果你使用靜態類由@Saeed – Pratik 2010-11-15 06:36:45
給出的答案做了,在該類的每個方法必須是靜態的,它是一種約束。但是如果你使用這種模式,你不必拘泥於這個約束。 – 2010-11-15 07:19:23
在這種情況下,你會用'A.GetA'方法實例類,你也可以有這個太多的情況下,你在做什麼?創建私有構造函數爲什麼?如果你想創建這樣的事情,你應該有理由叫什麼區別'一個一個新= A()'和'A中的= A.GetA()',如果你讓類的構造函數私有的,應該有一定的原因,例如,使它單身。或者使其從其他類的訪問中獲得私有權,但您可以在任何地方訪問它。 – 2010-11-15 10:41:12