산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# 정적 키워드

C# 정적 키워드

이 자습서에서는 예제를 통해 C#의 정적 키워드에 대해 알아봅니다.

C#에서 static을 사용하는 경우 키워드를 클래스 멤버와 함께 사용하면 유형 멤버의 단일 복사본이 생성됩니다.

또한 클래스의 모든 개체는 개별 복사본을 만드는 대신 단일 복사본을 공유합니다.

<시간>

C# 정적 변수

변수가 static으로 선언된 경우 , 클래스 이름을 사용하여 변수에 액세스할 수 있습니다. 예를 들어,

using System;

namespace StaticKeyword {

  class Student {

    // static variable
    public static string department = "Computer Science";
  }

  class Program {
    static void Main(string[] argos) {
    
      // access static variable
      Console.WriteLine("Department: " + Student.department);
     
      Console.ReadLine();
    }
  }
}

출력

Department: Computer Science

위의 예에서 department라는 정적 변수를 만들었습니다. . 변수는 정적이므로 클래스 이름 Student를 사용했습니다. 변수에 액세스합니다.

<시간>

정적 변수 대 인스턴스 변수

C#에서 클래스의 모든 개체에는 고유한 인스턴스 변수 복사본이 있습니다. 예를 들어,

class Student {

  // instance variable
  public string studentName;
 }

class Program {
  static void Main(string[] args) {

    Student s1 = new Student();
    Student s2 = new Student();
  }
}

여기서 두 개체 모두 s1s2 변수 studentName의 별도 복사본이 있습니다. . 그리고 그들은 서로 다릅니다.

그러나 변수를 static으로 선언하면 클래스의 모든 객체가 동일한 정적 변수를 공유합니다. 그리고 정적 변수에 접근하기 위해 클래스의 객체를 생성할 필요가 없습니다.

예:C# 정적 변수 대. 인스턴스 변수

using System;
 
namespace StaticKeyword {
 
  class Student {
    static public string schoolName = "Programiz School";
    public string studentName;
 
  }
 
    class Program {
    static void Main(string[] args) {
       
      Student s1 = new Student();
      s1.studentName = "Ram";

      // calls instance variable
      Console.WriteLine("Name: " + s1.studentName);
      // calls static variable
      Console.WriteLine("School: " + Student.schoolName);
 
      Student s2 = new Student();
      s2.studentName = "Shyam";
   
       // calls instance variable
      Console.WriteLine("Name: " + s2.studentName);
      // calls static variable
      Console.WriteLine("School: " + Student.schoolName);
      
      Console.ReadLine();
    }
  }
}

출력

Name: Ram
School: Programiz School
Name: Shyam
School: Programiz School

위 프로그램에서 Student 클래스에는 studentName이라는 비정적 변수가 있습니다. 및 schoolName이라는 정적 변수 .

프로그램 내부 클래스,

schoolName 이후 모든 학생에게 동일하므로 schoolName 공전. 메모리를 절약하고 프로그램을 보다 효율적으로 만듭니다.

<시간>

C# 정적 메서드

정적 변수와 마찬가지로 클래스 이름을 사용하여 정적 메서드를 호출할 수 있습니다.

class Test {

  public static void display() {....}

}

class Program {
  static void Main(string[] args) {

    Test.display();
  }
}

여기에서는 Program에서 직접 정적 메서드에 액세스했습니다. 클래스 이름을 사용하는 클래스.

정적 메서드를 선언하면 클래스의 모든 개체가 동일한 정적 메서드를 공유합니다.

예:C# 정적 및 비정적 메서드

using System;
 
namespace StaticKeyword {
 
  class Test {
 
    public void display1() {
 
      Console.WriteLine("Non static method");
    }
    public static void display2() {
 
      Console.WriteLine("Static method");
    }
  }
 
  class Program {
    static void Main(string[] args) {
 
      Test t1 = new Test();
      t1.display1();
      Test.display2();    
      Console.ReadLine();
    }
  }
}

출력

Non static method
Static method

위의 프로그램에서 display1()라는 비정적 메서드를 선언했습니다. 및 display2()라는 정적 메서드 테스트 클래스 내부 .

프로그램 클래스 내부

참고 :C#에서 메인 메서드는 정적입니다. 따라서 객체를 생성하지 않고 호출할 수 있습니다.

<시간>

C# 정적 클래스

C#에서 클래스를 static으로 선언하면 해당 클래스의 개체를 만들 수 없습니다. 예를 들어,

using System;

namespace StaticKeyword {

  static class Test {
    static int a = 5;
    static void display() {

      Console.WriteLine("Static method");
    }
  
    static void Main(string[] args) {

      // creating object of Test
      Test t1 = new Test();
      Console.WriteLine(a);
      display();
    }
  }
}

위의 예에는 정적 클래스 Test가 있습니다. . t1 개체를 만들었습니다. 테스트 클래스 .

정적 클래스의 개체를 만들 수 없으므로 다음 오류가 발생합니다.

error CS0723: Cannot declare a variable of static type 'Test' 
error CS0712: Cannot create an instance of the static class

정적 클래스 내부에 정적 멤버만 가질 수 있기 때문에 정적 클래스의 필드와 메소드도 정적임을 주목하십시오.

참고 :C#에서는 정적 클래스를 상속할 수 없습니다. 예를 들어,

static class A {
  ...
}

// Error Code
class B : A {
  ...
}
<시간>

클래스 내의 정적 멤버 액세스

동일한 클래스 내의 정적 변수와 메서드에 액세스하는 경우 클래스 이름을 사용하지 않고 직접 액세스할 수 있습니다. 예를 들어,

using System;
 
namespace StaticKeyword {
 
  class Test {
 
    static int age = 25;
    public static void display() {
 
      Console.WriteLine("Static method");
    }
   
    static void Main(string[] args) {
 
      Console.WriteLine(age);
      display();
      Console.ReadLine();
    }
  }
}

출력

25
Static method

여기에서 정적 필드 age에 액세스하고 있습니다. 및 정적 메서드 display() 클래스 이름을 사용하지 않고.


C 언어

  1. C# 클래스 및 개체
  2. C# 액세스 수정자
  3. C# 이 키워드
  4. C# 추상 클래스 및 메서드
  5. C# 중첩 클래스
  6. C# 부분 클래스 및 부분 메서드
  7. C# 봉인된 클래스 및 메서드
  8. Java의 정적 변수:정적 블록 및 메서드란 [예시]
  9. C++의 다형성
  10. C++의 데이터 추상화