# 靜態類別和靜態類別成員 (C# 程式設計手冊)

``````UtilityClass.MethodA();
``````

## 範例

``````public static class TemperatureConverter
{
public static double CelsiusToFahrenheit(string temperatureCelsius)
{
// Convert argument to double for calculations.
double celsius = 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 = Double.Parse(temperatureFahrenheit);

// Convert Fahrenheit to Celsius.
double celsius = (fahrenheit - 32) * 5 / 9;

return celsius;
}
}

class TestTemperatureConverter
{
static void Main()
{
Console.WriteLine("1. From Celsius to Fahrenheit.");
Console.WriteLine("2. From Fahrenheit to Celsius.");
Console.Write(":");

double F, C = 0;

switch (selection)
{
case "1":
Console.Write("Please enter the Celsius temperature: ");
Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
break;

case "2":
Console.Write("Please enter the Fahrenheit temperature: ");
Console.WriteLine("Temperature in Celsius: {0:F2}", C);
break;

default:
break;
}

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
}
}
/* Example Output:
1. From Celsius to Fahrenheit.
2. From Fahrenheit to Celsius.
:2
Please enter the Fahrenheit temperature: 20
Temperature in Celsius: -6.67
Press any key to exit.
*/
``````

## 靜態成員

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...
}
``````

``````Automobile.Drive();
int i = Automobile.NumberOfWheels;
``````

## C# 語言規格

• 10.1.1.3 靜態類別

C# 程式設計手冊

2008 年 7 月