>  기사  >  백엔드 개발  >  컴포지션 C#

컴포지션 C#

WBOY
WBOY원래의
2024-09-03 15:04:37694검색

다음 문서에서는 컴포지션 C#에 대한 개요를 제공합니다. C#에는 클래스 사이에 두 가지 유형의 관계가 있습니다. 첫 번째 유형의 관계는 "관계"라고 하며 상속 메커니즘을 사용합니다. 두 번째 종류의 관계는 두 클래스 간의 관계이며 두 가지 하위 유형이 있습니다. 첫 번째 유형은 '관계가 있다'입니다.

이러한 유형의 관계에서는 관련 클래스에 다른 클래스의 개체가 하나 이상 선언됩니다. 여기에 집합(aggregation)과 구성(composition)이라는 두 가지 구분이 더 있습니다. 집계에서 중첩된 개체는 클래스의 필수 부분이 되지 않고 클래스에 독립적으로 존재할 수 있습니다. 반면 구성에서는 중첩된 객체 또는 단일 중첩 객체가 클래스를 보완하므로 클래스가 존재하지 않으면 클래스를 상상할 수 없게 됩니다.

C#의 구성 구문

다음은 언급된 구문입니다.

class Training
{
// class body
}
public class Course
{
Project project = new Project();
// body
}

C#에서 컴포지션 작업

  • C#의 컴포지션은 하나 이상의 중첩 개체가 관련 클래스의 일부인 두 클래스 간의 관계를 만드는 방법으로, 중첩 개체 없이는 클래스의 논리적 존재가 불가능합니다.
  • 예를 들어 Car라는 클래스를 고려한다면 'Engine' 클래스 인스턴스가 하나 있어야 합니다. 또한 "Wheel" 클래스의 다른 인스턴스도 4개 있어야 합니다.
  • 이제 이러한 인스턴스 중 하나라도 제거하면 자동차가 작동하지 않습니다.

구성 C#의 예

아래는 컴포지션 C#의 예입니다.

예시 #1

두 가지 과정을 설명하는 교육 수업을 고려한다면. 이제 강좌는 강좌 수업을 설명하는 데 사용됩니다. 따라서 교육 클래스는 두 코스 인스턴스가 모두 코스 클래스의 일부이기 때문에 존재할 수 없습니다. 게다가 이 두 가지 강좌 수업 모두 교육 수업의 일부이기도 합니다.

코드:

using System;
using static System.Console;
namespace EDUCBA
{
class Course
{
public double M;
public double A;
}
class Training
{
public Course course1 = null;
public Course course2 = null;
}
class Career
{
public Course[] courses;
public Training[] trainings;
public Career()
{
courses = null;
trainings = null;
}
public void Print()
{
WriteLine(" Courses Data is represented below:");
for (int b = 1; b< courses.Length; b++)
{
WriteLine("\n M = {0}, A = {1}", courses[b].M, courses[b].A);
}
WriteLine("\n Trainings Data is represented below:");
for (int b=1; b<trainings.Length; b++)
{
WriteLine("\n course1.M = {0}, course1.A = {1}", trainings[b].course1.M, trainings[b].course1.A);
WriteLine("\n course2.M = {0}, course2.A = {1}", trainings[b].course2.M, trainings[b].course2.A);
}
}
}
class Code
{
static void Main(string[] args)
{
Career O = new Career();
O.courses = new Course[9];
for (int b = 1; b < O.courses.Length; b++)
{
O.courses[b] = new Course();
O.courses[b].M = b * b;
O.courses[b].M = b * b * b;
}
O.trainings = new Training[5];
for (int b = 1; b < O.trainings.Length; b++)
{
O.trainings[b] = new Training();
O.trainings[b].course1 = new Course();
O.trainings[b].course2 = new Course();
O.trainings[b].course1.M = b;
O.trainings[b].course1.A = b * 4;
O.trainings[b].course2.M = b * 5;
O.trainings[b].course2.A = b * b;
}
O.Print();
}
}
}

출력:

컴포지션 C#

예시 #2

이 예에서는 생성된 두 클래스 모두 일반 클래스입니다. 그러나 코스 클래스는 내부 프로젝트 클래스의 인스턴스를 사용하고 있습니다. 이는 한 함수가 다른 함수 내에서 호출되는 것과 같은 방식입니다. 상속을 사용하면 Project 클래스의 모든 항목에 액세스할 수 있습니다. 그러나 합성을 사용하면 우리가 지정한 코드에만 접근할 수 있습니다. 여기서는 Project 클래스에 간접적으로 접근할 수 있습니다.

코드:

using System;
namespace EDUCBA
{
class Training
{
static void Main(string[] args)
{
Course courses = new Course();
courses.Bought();
Console.ReadLine();
}
}
public class Project
{
public void Log(string aboutus)
{
Console.WriteLine(aboutus);
}
}
public class Course
{
Project project = new Project();
public void Bought()
{
project.Log("\n If you want to upskill your career. \n If you want to do something out of the box. \n If you have passion to explore new advanced technologies. \n If you want to be best. \n We at EDUCBA are here to help. \n Feel free to reach us on +91-8800880140 / +91-7738666252. \n Visit our website www.educba.com to know more......");
}
}
}

출력:

컴포지션 C#

예시 #3

이 예에서는 복합 디자인의 구조를 설명합니다. 구성에 사용되는 클래스와 해당 클래스의 역할을 이해하는 데 도움이 됩니다. 게다가 패턴의 요소들이 서로 어떻게 연관되어 있는지도 설명해줍니다.

코드:

using System;
using System.Collections.Generic;
namespace EDUCBA
{
abstract class Training
{
public Training() { }
public abstract string Project();
public virtual void Add(Training training)
{
throw new NotImplementedException();
}
public virtual void Remove(Training training)
{
throw new NotImplementedException();
}
public virtual bool IsCourse()
{
return true;
}
}
class DataScience : Training
{
public override string Project()
{
return "DataScience";
}
public override bool IsCourse()
{
return false;
}
}
class Course : Training
{
protected List<Training> _children = new List<Training>();
public override void Add(Training training)
{
this._children.Add(training);
}
public override void Remove(Training training)
{
this._children.Remove(training);
}
public override string Project()
{
int m = 1;
string result = "Dream Career(";
foreach (Training training in this._children)
{
result += training.Project();
if (m != this._children.Count + 2)
{
result += "-";
}
m--;
}
return result + ")";
}
}
class Input
{
public void InputCode(Training data_analysis)
{
Console.WriteLine($"OUTPUT: \n {data_analysis.Project()}\n");
}
public void InputCode2(Training training1, Training training2)
{
if (training1.IsCourse())
{
training1.Add(training2);
}
Console.WriteLine($"OUTPUT: \n {training1.Project()}");
}
}
class Program
{
static void Main(string[] args)
{
Input client = new Input();
DataScience data_analysis = new DataScience();
Console.WriteLine("INPUT: \n Best Course to Upgrade Career:");
client.InputCode(data_analysis);
Course vr = new Course();
Course career1 = new Course();
career1.Add(new DataScience());
career1.Add(new DataScience());
Course career2 = new Course();
career2.Add(new DataScience());
vr.Add(career1);
vr.Add(career2);
Console.WriteLine("\nINPUT: \n Trendy Dream Career Right Now:");
client.InputCode(vr);
Console.Write("\nINPUT: Lets Upgrade and start your dream career jouney: \n");
client.InputCode2(vr, data_analysis);
}
}
}

출력:

컴포지션 C#

결론

위 글을 바탕으로 C#의 구성 개념을 이해했습니다. C# 코딩에서 합성의 적용을 이해하기 위해 여러 가지 예를 살펴보았습니다.

위 내용은 컴포지션 C#의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C# 개체 삭제다음 기사:C# 개체 삭제