C# 속성 및 인덱서
1. 속성
소위 속성은 실제로 비공개 클래스 필드에 대한 제어된 액세스를 구현하는 특수 클래스 멤버입니다. C# 언어에는 두 가지 속성 메서드가 있습니다. 하나는 private 필드의 값을 반환할 수 있는 get이고, 두 번째는 private 필드의 값을 설정할 수 있는 set입니다. 예를 들어, 학생 이름 속성을 생성하고 이름 필드에 대한 제어된 액세스를 제어하려면 다음 코드를 예로 들어 보겠습니다.
using System; public class Student { private string name; /// <summary> /// 定义学生的姓名属性 /// </summary> public string Name { get { return name; } set { name = value; } } } class Program { static void Main(string[] args) { Student student = new Student(); student.Name = "Jeff Wong"; Console.WriteLine(student.Name); Console.Read(); } }
2. 인덱서
간단히 말해, 소위 인덱서는 배열처럼 자신의 클래스를 참조할 수 있는 특수 속성 유형입니다. 분명히 이 기능은 컬렉션 클래스를 생성할 때 특히 유용하지만, 대용량 파일을 처리하거나 특정 제한된 리소스를 추상화하는 등의 다른 상황에서는 클래스에서 배열과 유사한 동작을 갖는 것도 매우 유용합니다. 예를 들어, 위의 예에서는 한 학급에 여러 명의 학생이 있다고 가정합니다. 인덱서 구축은 쉽게 호출할 수 있습니다.
using System; using System.Collections.Generic; public class Student { public List<Student> listStudents = new List<Student>(); /// <summary> /// 构建索引器 /// </summary> /// <param name="i"></param> /// <returns></returns> public Student this[int i] { get { return listStudents[i]; } set { listStudents[i] = value; } } private string name; /// <summary> /// 属性 /// </summary> public string Name { get { return name; } set { name = value; } } public Student(string name) { this.name = name; } public Student() { this.listStudents.Add(new Student("jeff wong")); this.listStudents.Add(new Student("jeffery zhao")); this.listStudents.Add(new Student("terry lee")); this.listStudents.Add(new Student("dudu")); } } class Program { static void Main(string[] args) { Student student = new Student(); int num = student.listStudents.Count; Console.WriteLine("All the students:"); for (int i = 0; i < num; i++) { Console.WriteLine(student[i].Name); //通过索引器,取所有学生名 } //设置索引器的值 student[0].Name = "jeff"; Console.WriteLine("After modified,all the students:"); for (int i = 0; i < num; i++) { Console.WriteLine(student[i].Name); } Console.Read(); } }
위 코드에서 인덱서의 접근자는 매개변수가 하나인 경우(매개변수는 정수) 실제로 여러 매개변수가 포함된 인덱서를 구축할 수 있습니다. 위의 코드를 예로 들면, 학생의 학번과 이름을 기준으로 학생의 총점을 구하고 싶습니다. 수정된 코드는 다음과 같습니다.
using System; using System.Collections.Generic; public class Student { public List<Student> listStudents = new List<Student>(); public Student this[int i,string name] { get { foreach (Student stu in listStudents.ToArray()) { if (stu.sid == i && stu.name == name) //按照学号和姓名取出学生 { return stu; } } return null; } set { listStudents[i] = value; } } private int sid; //学号 public int Sid { get { return sid; } set { sid = value; } } private string name;//姓名 public string Name { get { return name; } set { name = value; } } private int score; //总分 public int Score { get { return score; } set { score = value; } } public Student(int sid, string name, int score) { this.sid = sid; this.name = name; this.score = score; } public Student() { this.listStudents.Add(new Student(1, "jeff wong", 375)); this.listStudents.Add(new Student(2,"jeffery zhao",450)); this.listStudents.Add(new Student(3,"terry lee",400)); this.listStudents.Add(new Student(4,"dudu",500)); } } class Program { static void Main(string[] args) { Student student = new Student(); Student stu = student[1, "jeff wong"]; Console.WriteLine("student number:" + stu.Sid + ",name:" + stu.Name + ",score:" + stu.Score); Console.Read(); } }
요약:
< ;1>,
속성 정의:
액세스 한정자 반환 유형 속성 이름
{
get{Statement 컬렉션}
set{Statement 컬렉션}
}
인덱서 정의:
액세스 한정자 반환 유형 this[매개변수 유형 매개변수...]
{
get{statement collection}
set {문 컬렉션 }
}
<2>,
인덱서를 사용하면 배열과 비슷한 방식으로 객체를 인덱싱할 수 있습니다.
인덱서를 정의하는 데 사용되는 키워드입니다.
접속자 반환 값을 가져옵니다. set 접근자는 값을 할당합니다.
값 키워드는 집합 인덱서가 할당한 값을 정의하는 데 사용됩니다.
인덱서는 정수 값을 기반으로 인덱싱할 필요가 없으며 특정 조회 메커니즘을 정의하는 것은 사용자의 몫입니다.
인덱서는 오버로드될 수 있습니다.
<3> 속성과 인덱서의 주요 차이점은 다음과 같습니다.
a. 클래스의 각 속성에는 고유한 이름이 있어야 하며, 클래스에 정의된 각 인덱서에는 고유한 서명이 있어야 합니다. 인덱서 오버로딩이 구현될 수 있도록).
b. 속성은 정적(정적)일 수 있으며 인덱서는 인스턴스 멤버여야 합니다.
<4>, 인덱서 오버로딩 예:
using System; using System.Collections.Generic; public class Student { public List<Student> listStudents = new List<Student>(); public Student this[int i,string name] { get { foreach (Student stu in listStudents.ToArray()) { if (stu.sid == i && stu.name == name) //按照学号和姓名取出学生 { return stu; } } return null; } set { listStudents[i] = value; } } /// <summary> /// 索引器重载 /// </summary> /// <param name="i"></param> /// <returns></returns> public Student this[int i] //i从0开始 { get { return listStudents[i]; } set { listStudents[i] = value; } } private int sid; //学号 public int Sid { get { return sid; } set { sid = value; } } private string name;//姓名 public string Name { get { return name; } set { name = value; } } private int score; //总分 public int Score { get { return score; } set { score = value; } } public Student(int sid, string name, int score) { this.sid = sid; this.name = name; this.score = score; } public Student() { this.listStudents.Add(new Student(1, "jeff wong", 375)); this.listStudents.Add(new Student(2,"jeffery zhao",450)); this.listStudents.Add(new Student(3,"terry lee",400)); this.listStudents.Add(new Student(4,"dudu",500)); } } class Program { static void Main(string[] args) { Student student = new Student(); Student stu = student[1, "jeff wong"]; Console.WriteLine("student number:" + stu.Sid + ",name:" + stu.Name + ",score:" + stu.Score); Console.WriteLine("all the students:"); for (int i = 0; i < student.listStudents.Count; i++) { Console.WriteLine("student number:" + student[i].Sid + ",name:" + student[i].Name + ",score:" + student[i].Score); } Console.Read(); } }
더 많은 C# 속성 및 인덱서 관련 기사를 참고하세요. PHP 중국어 웹사이트!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









char 어레이는 문자 시퀀스를 C 언어로 저장하고 char array_name [size]로 선언됩니다. 액세스 요소는 첨자 연산자를 통해 전달되며 요소는 문자열의 끝점을 나타내는 널 터미네이터 '\ 0'으로 끝납니다. C 언어는 strlen (), strcpy (), strcat () 및 strcmp ()와 같은 다양한 문자열 조작 함수를 제공합니다.

C 언어에서 특수 문자는 다음과 같은 탈출 시퀀스를 통해 처리됩니다. \ n 라인 브레이크를 나타냅니다. \ t는 탭 문자를 의미합니다. char c = '\ n'과 같은 특수 문자를 나타 내기 위해 탈출 시퀀스 또는 문자 상수를 사용하십시오. 백 슬래시는 두 번 탈출해야합니다. 다른 플랫폼과 컴파일러마다 다른 탈출 시퀀스가있을 수 있습니다. 문서를 참조하십시오.

C에서 숯 유형은 문자열에 사용됩니다. 1. 단일 문자를 저장하십시오. 2. 배열을 사용하여 문자열을 나타내고 널 터미네이터로 끝납니다. 3. 문자열 작동 함수를 통해 작동합니다. 4. 키보드에서 문자열을 읽거나 출력하십시오.

멀티 스레딩과 비동기식의 차이점은 멀티 스레딩이 동시에 여러 스레드를 실행하는 반면, 현재 스레드를 차단하지 않고 비동기식으로 작업을 수행한다는 것입니다. 멀티 스레딩은 컴퓨팅 집약적 인 작업에 사용되며 비동기식은 사용자 상호 작용에 사용됩니다. 멀티 스레딩의 장점은 컴퓨팅 성능을 향상시키는 것이지만 비동기의 장점은 UI 스레드를 차단하지 않는 것입니다. 멀티 스레딩 또는 비동기식을 선택하는 것은 작업의 특성에 따라 다릅니다. 계산 집약적 작업은 멀티 스레딩을 사용하고 외부 리소스와 상호 작용하고 UI 응답 성을 비동기식으로 유지 해야하는 작업을 사용합니다.

C 언어 커버 산술, 할당, 조건, 논리, 비트 연산자 등의 기호의 사용 방법은 기본 수학 연산에 사용되며, 할당 연산자는 할당 및 추가, 곱하기, 분할 할당에 사용되며, 곱하기 및 분할 할당에 사용되며, 조건에 따라 조건 운영자가 사용되며, 비트 오퍼레이터에 사용되며, 스페셜 오퍼레이터는 비트 수준의 운영에 사용됩니다. 포인터, 파일 종료 마커 및 비수통 값.

C 언어에서 숯 유형 변환은 다른 유형으로 직접 변환 할 수 있습니다. 캐스팅 : 캐스팅 캐릭터 사용. 자동 유형 변환 : 한 유형의 데이터가 다른 유형의 값을 수용 할 수 있으면 컴파일러가 자동으로 변환됩니다.

C 언어에는 내장 합계 기능이 없으므로 직접 작성해야합니다. 합계는 배열 및 축적 요소를 가로 질러 달성 할 수 있습니다. 루프 버전 : 루프 및 배열 길이를 사용하여 계산됩니다. 포인터 버전 : 포인터를 사용하여 배열 요소를 가리키며 효율적인 합계는 자체 증가 포인터를 통해 달성됩니다. 동적으로 배열 버전을 할당 : 배열을 동적으로 할당하고 메모리를 직접 관리하여 메모리 누출을 방지하기 위해 할당 된 메모리가 해제되도록합니다.

C 언어에서 char와 wchar_t의 주요 차이점은 문자 인코딩입니다. char ascii를 사용하거나 ascii를 확장하고, wchar_t는 유니 코드를 사용합니다. Char는 1-2 바이트를 차지하고 WCHAR_T는 2-4 바이트를 차지합니다. Char는 영어 텍스트에 적합하며 WCHAR_T는 다국어 텍스트에 적합합니다. Char_t는 널리 지원되며, 컴파일러 및 운영 체제가 유니 코드를 지원하는지 여부에 따라 다릅니다. Char는 문자 범위가 제한되며 WCHAR_T는 더 큰 문자 범위를 가지며 특수 함수는 산술 작업에 사용됩니다.
