CLR笔记:9.Property2011-10-26 博客园 包建强属性分两种,无参属性,有参属性,后者又叫索引器(indexer)——VB.NET中相应为默认属性。1.无参属性CLR支持静态属性,实例属性,抽象属性,虚拟属性,但不能被重载。属性在MSIL中生成以下内容:get_XX方法,当在属性中定义了get的时候——XX为属性名set_XX方法,当在属性中定义了set的时候——XX为属性名一个位于原数据中的属性定义。属性不能作为out/ref传递给方法,字段则可以。如果属性中执行语句过多,要花很多时间,这时候优先选用方法。例如线程同步和Remoting。多次访问属性,每次返回的值可能不同;而字段的值每次返回都不会改变。例如System.DateTime属性 ——MS以后会将其改为方法。2.有参属性定义,有参属性的get方法可以接受1个或者更多参数,set方法可以接受2个或者更多参数——对比,无参属性get方法无参数,set方法有1个参数。C#索引器语法,是对[ ]这个运算符的重载,示例如下:
public class FailSoftArray { int[] a; public int length; public FailSoftArray(int length) { a = new int[length]; this.length = length; } public int this[int index] { get { if (index >= 0 & index < length) { return a[index]; } else throw new ArgumentOutOfRangeException(); } set { if (index >= 0 & index < length) { a[index] = value; } else throw new ArgumentOutOfRangeException(); } } } public class TestIndex { public TestIndex() { FailSoftArray fs = new FailSoftArray(5); for (int i = 0; i < 5; i++) { fs[i] = i * 10; } } }