Static int си шарп

Static Classes and Static Class Members (C# Programming Guide)

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public static method named MethodA , you call the method as shown in the following example:

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name, as shown in the following example.

double dub = -3.14; Console.WriteLine(Math.Abs(dub)); Console.WriteLine(Math.Floor(dub)); Console.WriteLine(Math.Round(Math.Abs(dub))); // Output: // 3.14 // -4 // 3 

As is the case with all class types, the type information for a static class is loaded by the .NET runtime when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

Читайте также:  Css style all but last

To create a non-static class that allows only one instance of itself to be created, see Implementing Singleton in C#.

The following list provides the main features of a static class:

  • Contains only static members.
  • Cannot be instantiated.
  • Is sealed.
  • Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class or interface except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization. For more information, see Static Constructors.

Example

Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius:

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("Please select the convertor direction"); Console.WriteLine("1. From Celsius to Fahrenheit."); Console.WriteLine("2. From Fahrenheit to Celsius."); Console.Write(":"); string? selection = Console.ReadLine(); double F, C = 0; switch (selection) < case "1": Console.Write("Please enter the Celsius temperature: "); F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine() ?? "0"); Console.WriteLine("Temperature in Fahrenheit: ", F); break; case "2": Console.Write("Please enter the Fahrenheit temperature: "); C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine() ?? "0"); Console.WriteLine("Temperature in Celsius: ", C); break; default: Console.WriteLine("Please select a convertor."); break; > // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); > > /* Example Output: Please select the convertor direction 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. */ 

Static Members

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it’s explicitly passed in a method parameter.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static. Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.

Although a field cannot be declared as static const , a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that’s used for static fields. No object instance is required.

C# does not support static local variables (that is, variables that are declared in method scope).

You declare static class members by using the static keyword before the return type of the member, as shown in the following 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 there is one, 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, as shown in the following example:

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

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.

A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for null object references. However, most of the time the performance difference between the two is not significant.

C# Language Specification

For more information, see Static classes, Static and instance members and Static constructors in the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also

Источник

static (Справочник по C#)

На этой странице приводятся сведения о ключевом слове модификатора static . Ключевое слово static также является частью директивы using static .

Модификатор static используется для объявления статического члена, принадлежащего собственно типу, а не конкретному объекту. Модификатор static можно использовать для объявления классов static . В классах, интерфейсах и структурах вы можете добавить модификатор static к полям, методам, свойствам, операторам, событиям и конструкторам. Модификатор static запрещено использовать с индексаторами или методами завершения. Дополнительные сведения см. в статье Статические классы и члены статических классов.

Модификатор static можно добавить в локальную функцию. Статическая локальная функция не может сохранять локальные переменные или состояние экземпляра.

Начиная с C# 9.0 можно добавить модификатор static в лямбда-выражение или анонимный метод. Статическое лямбда-выражение или анонимный метод не могут сохранять локальные переменные или состояние экземпляра.

Пример: статический класс

Следующий класс объявляется как static и содержит только методы static :

static class CompanyEmployee < public static void DoSomething() < /*. */ >public static void DoSomethingElse() < /*. */ >> 

Объявление константы или типа неявно является членом static . На член static невозможно ссылаться через экземпляр, а можно только через имя типа. Например, рассмотрим следующий класс.

Чтобы обратиться к члену static x , воспользуйтесь полным именем — MyBaseC.MyStruct.x (если только член не доступен из той же области действия).

Console.WriteLine(MyBaseC.MyStruct.x); 

Так как экземпляр класса содержит отдельную копию всех полей экземпляра класса, каждому полю static соответствует только одна копия.

Невозможно использовать this для ссылки на методы static или методы доступа к свойствам.

Если к классу применяется ключевое слово static , все члены этого класса должны быть static .

Классы, интерфейсы и классы static могут иметь конструкторы static . Конструктор static вызывается на определенном этапе между запуском программы и созданием экземпляра класса.

Ключевое слово static имеет более ограниченное применение по сравнению с C++. Сведения о сравнении с ключевым словом С++ см. в статье Классы хранения (C++).

В качестве демонстрации членов static рассмотрим класс, представляющий сотрудника компании. Предположим, что этот класс содержит метод для подсчета сотрудников и поле для хранения их числа. И метод, и поле не принадлежат никакому экземпляру сотрудника. Они принадлежат всему классу сотрудников. В связи с этим они должны объявляться как члены static класса.

Пример: статическое поле и метод

В этом примере выполняется чтение имени и идентификатора нового сотрудника, увеличение счетчика сотрудников на единицу, а также отображение сведений о новом сотруднике и новом числе сотрудников. Эта программа считывает текущее число сотрудников с клавиатуры.

public class Employee4 < public string id; public string name; public Employee4() < >public Employee4(string name, string id) < this.name = name; this.id = id; >public static int employeeCounter; public static int AddEmployee() < return ++employeeCounter; >> class MainClass : Employee4 < static void Main() < Console.Write("Enter the employee's name: "); string name = Console.ReadLine(); Console.Write("Enter the employee's ID: "); string // Create and configure the employee object. Employee4 e = new Employee4(name, id); Console.Write("Enter the current number of employees: "); string n = Console.ReadLine(); Employee4.employeeCounter = Int32.Parse(n); Employee4.AddEmployee(); // Display the new information. Console.WriteLine($"Name: "); Console.WriteLine($"ID: "); Console.WriteLine($"New Number of Employees: "); > > /* Input: Matthias Berndt AF643G 15 * Sample Output: Enter the employee's name: Matthias Berndt Enter the employee's ID: AF643G Enter the current number of employees: 15 Name: Matthias Berndt ID: AF643G New Number of Employees: 16 */ 

Пример: статическая инициализация

В этом примере показано, как можно инициализировать поле static , используя другое поле static , которое еще не объявлено. Результаты будут неопределенными до тех пор, пока вы явно не присвоите значение полю static .

class Test < static int x = y; static int y = 5; static void Main() < Console.WriteLine(Test.x); Console.WriteLine(Test.y); Test.x = 99; Console.WriteLine(Test.x); >> /* Output: 0 5 99 */ 

Спецификация языка C#

Дополнительные сведения см. в спецификации языка C#. Спецификация языка является предписывающим источником информации о синтаксисе и использовании языка C#.

См. также

Источник

Оцените статью