>  기사  >  백엔드 개발  >  C# 속성 및 인덱서

C# 속성 및 인덱서

高洛峰
高洛峰원래의
2016-12-17 09:26:291141검색

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 {문 컬렉션 }

2cc198a1d5eb0d3eb508d858c9f5cbdb,

인덱서를 사용하면 배열과 비슷한 방식으로 객체를 인덱싱할 수 있습니다.
인덱서를 정의하는 데 사용되는 키워드입니다.
접속자 반환 값을 가져옵니다. set 접근자는 값을 할당합니다.
값 키워드는 집합 인덱서가 할당한 값을 정의하는 데 사용됩니다.
인덱서는 정수 값을 기반으로 인덱싱할 필요가 없으며 특정 조회 메커니즘을 정의하는 것은 사용자의 몫입니다.
인덱서는 오버로드될 수 있습니다.
5bdf4c78156c7953567bb5a0aef2fc53 속성과 인덱서의 주요 차이점은 다음과 같습니다.
a. 클래스의 각 속성에는 고유한 이름이 있어야 하며, 클래스에 정의된 각 인덱서에는 고유한 서명이 있어야 합니다. 인덱서 오버로딩이 구현될 수 있도록).
b. 속성은 정적(정적)일 수 있으며 인덱서는 인스턴스 멤버여야 합니다.
23889872c2e8594e0f446a471a78ec4c, 인덱서 오버로딩 예:

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 중국어 웹사이트!


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