logo
CSharp_Prog_Guide

Когда следует использовать статические классы

Предположим, что имеется класс CompanyInfo, содержащий следующие методы получения сведений о названии компании и ее адресе.

class CompanyInfo

{

public string GetCompanyName() { return "CompanyName"; }

public string GetCompanyAddress() { return "CompanyAddress"; }

//...

}

Эти методы не обязательно должны быть присоединены к определенному экземпляру класса. Следовательно, вместо создания ненужных экземпляров этого класса можно объявить его как статический класс.

static class CompanyInfo

{

public static string GetCompanyName() { return "CompanyName"; }

public static string GetCompanyAddress() { return "CompanyAddress"; }

//...

}

Используйте статический класс в качестве организационной единицы для методов, не связанных с определенными объектами. Кроме того, статический класс позволяет упростить и ускорить реализацию, поскольку нет необходимости создавать объект, чтобы вызывать его методы. Рекомендуется упорядочить методы внутри класса понятным образом. В качестве примера можно привести методы класса Math в пространстве имен System.

Static Members

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for example, a math library might contain static methods for calculating sine and cosine.

Static methods can be overloaded but not overridden.

Static class members are declared by using the static keyword before the return type of the member, for example:

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

}

Static members are initialized before the static member is accessed for the first time and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

Automobile.Drive();

int i = Automobile.NumberOfWheels;