C# 구조체와 클래스

WBOY
풀어 주다: 2024-09-03 15:07:59
원래의
648명이 탐색했습니다.

이름에서 알 수 있듯이 C#에서는 'struct' 키워드를 사용하여 값 유형을 정의하고, Class는 'class' 키워드를 사용하여 참조 유형을 정의합니다. C#에서는 구조체에 정의된 변수를 스택이나 주어진 변수형에 저장하고, 인스턴스를 구조체 변수라고 합니다. 반면, '클래스'의 경우 인스턴스는 객체로 호출되며 힙 구조의 메모리 단위에 저장됩니다. 생성자와 소멸자의 측면에서 C# 구조체는 소멸자를 가질 수 없지만 클래스는 소멸자를 가질 수 있습니다. 클래스에서는 추상형, 가상형, 보호형 등 회원 분류가 허용됩니다.

C# 구조체와 클래스의 일대일 비교(인포그래픽)

다음은 C# 구조체와 클래스의 주요 14가지 차이점입니다.

C# 구조체와 클래스

C# 구조체와 클래스의 주요 차이점

C# 구조체와 클래스의 주요 차이점은 다음과 같습니다.

  1. 구조체는 'struct' 키워드를 사용하여 선언할 수 있고, 클래스는 'class' 키워드를 사용하여 선언할 수 있습니다.
  2. 구조체는 값 유형이므로 구조체 유형 변수는 구조체 데이터로 직접 구성되는 반면, 클래스는 참조 유형이고 클래스 유형 변수는 클래스의 객체라고 하는 데이터에 대한 참조로 구성됩니다.
  3. 클래스 유형 변수는 힙에 할당되며 가비지 수집될 수 있는 반면, 구조체 유형 변수는 스택 또는 포함 유형의 인라인에 할당됩니다.
  4. 클래스 객체는 'new' 키워드를 사용하여 생성되는 반면, 구조체 객체는 'new' 키워드를 사용하거나 사용하지 않고 생성할 수 있습니다. 'new' 연산자를 사용하지 않고 구조체를 인스턴스화하면 사용자가 해당 메서드, 속성 또는 이벤트에 액세스할 수 없습니다.
  5. 구조체의 각 변수에는 데이터 복사본(ref 및 out 매개변수 변수 제외)이 포함되어 있으므로 한 변수에 수행된 수정 사항은 다른 변수에 영향을 주지 않는 반면, 클래스에서는 두 개 이상의 변수가 동일한 개체와 수행된 모든 수정 사항을 참조할 수 있습니다. 하나의 변수가 다른 변수에 영향을 미칠 수 있습니다. 아래 예시를 통해 이 점을 이해할 수 있습니다.

struct를 사용한 예

코드:

using System;
namespace structAndClass
{
//creating structure
public struct Demo
{
public int x, y;
//parameterized constructor
public Demo(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class StructDemo
{
public static void Main(string[] args)
{
Demo a = new Demo(50, 50);
Demo b = a;
a.x = 100;
Console.WriteLine("Value of a.x = "+a.x);
Console.WriteLine("Value of b.x = "+b.x);
}
}
}
로그인 후 복사

출력:

C# 구조체와 클래스

클래스 사용 예시

코드:

using System;
namespace structAndClass
{
public class Demo
{
public int x, y;
public Demo(int x, int y)
{
this.x = x;
this.y = y;
}
}
public class StructDemo
{
public static void Main(string[] args)
{
Demo a = new Demo(50, 50);
Demo b = a;
a.x = 100;
Console.WriteLine("Value of a.x = "+a.x);
Console.WriteLine("Value of b.x = "+b.x);
}
}
}
로그인 후 복사

출력:

C# 구조체와 클래스

  1. 구조체 유형은 클래스 유형보다 메모리 할당 및 할당 해제 비용이 저렴합니다.
  2. 구조체는 매개변수 없는 인스턴스 생성자를 가질 수 없으며 매개변수화된 생성자 또는 정적 생성자를 가질 수 있지만 클래스는 매개변수 없는 기본 생성자를 가질 수 있습니다.
  3. 구조체에는 소멸자가 있을 수 없지만 클래스에는 소멸자가 있을 수 있습니다.
  4. 다른 구조체나 클래스에서 구조체를 상속할 수 없고 클래스의 기본이 될 수 없지만, 다른 클래스에서 클래스를 상속할 수 있으며 클래스는 다른 클래스의 기본이 될 수 있습니다. 따라서 클래스는 상속을 지원하지만 구조는 상속을 지원하지 않습니다.
  5. 구조체의 멤버를 abstract, virtual 또는 protected로 지정할 수는 없지만 클래스의 멤버는 abstract, virtual 또는 protected로 지정할 수 있습니다.
  6. 클래스의 인스턴스를 객체라고 하고, 구조체의 인스턴스를 구조체 변수라고 합니다.
  7. 액세스 지정자를 지정하지 않은 경우 클래스의 멤버는 기본적으로 비공개인 반면 구조체의 멤버는 기본적으로 공개됩니다.
  8. 클래스는 복잡한 데이터 구조에 사용되고, 구조는 작은 데이터 구조에 사용됩니다.

C# 구조체와 클래스 비교표

명확한 이해를 위해 비교표를 통해 C# 구조체와 클래스의 차이점을 더 살펴보겠습니다.

Parameter C# Struct Class
Data type The structure is a value type of data type. Class is a reference type data type.
Keyword The structure can be defined using the ‘struct’ keyword. The class can be defined using the ‘class’ keyword.
Storage area The structure variable is stored either in stack or inline in containing type. The object of the class is stored in heap.
Instance creation The instance of a struct can be created with or without a ‘new’ keyword. The instance of the class is created using a ‘new’ keyword.
Assignment If we make an assignment to a variable of struct type then it creates a copy of the value being assigned. Thus, each variable instructs has its copy of data. If we make an assignment to a variable of class type then it copies the reference. Thus, two or more variables in class can refer to the same object.
Constructor The structure does not contain a parameterless instance constructor. The class contains a parameterless instance constructor, if not defined explicitly by the user.
Destructor It cannot have a destructor. It can have a destructor.
Inheritance The structure cannot inherit from another class or structure.

The structure cannot be used as a base for another structure or class.

The class can inherit from another class. The class can be a base class for another class.
Data members Members of a struct cannot be abstract, virtual or protected. Members of a class can be abstract, virtual or protected.
Instance The instance of the structure is called the structure variable. The instance of the class is called an object.
Default access specifier Members of the structure are public by default. Members of the class are private by default.
Usage The structure can be used for small data structures. Class is used for the complex data structure.
Garbage collection The instance of a struct cannot be garbage collected. The instance of the class can be garbage collected.
Variable initializing Including variable initializer is not allowed while making instance field declarations instruct. Including variable initializer is allowed while making instance field declarations in a class.

결론

클래스와 구조 모두 관련 데이터 항목을 보유하는 데 사용됩니다. 많은 수의 데이터에는 클래스를 사용할 수 있고, 작은 데이터에는 구조를 사용할 수 있습니다. 클래스는 참조 유형이고 힙에 저장되는 반면 구조는 값 유형이며 스택에 저장됩니다.

위 내용은 C# 구조체와 클래스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!