unity基础学习十三,C#高级属性:属性(Property)和索引器C# 索引器(Indexer)
C# 中的属性和索引器
在C#中,属性(Properties)和索引器(Indexers)是两种用于访问对象成员的机制。它们提供了对类、结构或接口的封装,并允许开发者以更直观和灵活的方式操作数据。
属性(Properties)
属性是类、结构或接口的成员,可以用来读取或设置其内部状态。属性通常由一个 get 访问器和/或一个 set 访问器组成。
基本语法
public class Person { private string name; // 属性 public string Name { get { return name; } set { name = value; } } } 自动实现的属性
对于简单的属性,可以使用自动实现的属性(Auto-implemented properties),编译器会自动生成一个私有字段来存储属性值。
public class Person { // 自动实现的属性 public string Name { get; set; } } 只读和只写属性
- 只读属性:只有
get访问器。 - 只写属性:只有
set访问器。
public class Person { private int age; // 只读属性 public int Age { get { return age; } } // 只写属性 public void SetAge(int value) { age = value; } } 索引器(Indexers)
索引器允许类、结构或接口像数组一样被索引。索引器通过 this 关键字定义,可以接受一个或多个参数。
基本语法
public class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; // 索引器 public string this[int index] { get { if (index >= 0 && index <= size - 1) return namelist[index]; else return ""; } set { if (index >= 0 && index <= size - 1) namelist[index] = value; } } public IndexedNames() { for (int i = 0; i < size; i++) { namelist[i] = "N. A."; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; Console.WriteLine(names[0]); // 输出: Zara } } 重载索引器
索引器可以被重载,允许使用不同的参数类型。
public class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; // 索引器 public string this[int index] { get { return namelist[index]; } set { namelist[index] = value; } } // 重载的索引器 public int this[string name] { get { for (int i = 0; i < size; i++) { if (namelist[i] == name) return i; } return -1; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; Console.WriteLine(names["Zara"]); // 输出: 0 } } 总结
- 属性:用于读取和设置类的内部状态,通常使用
get和set访问器。 - 索引器:允许类像数组一样被索引,通过
this关键字定义。
通过合理使用属性和索引器,可以提高代码的可读性和可维护性。