实际上,只有一个 getter 和 setter。从技术上讲,IIRC CLI 规范(ECMA 335 第 1.8.11.3 节)不仅限于这些,因此其他一些语言可以自由添加其他含义,但实际上没有。
这显示在 table 中II.17
,并使用.other
IL 中的标题(注意它.get
用于 getter、.set
setter 和.custom
属性)。
编辑
特别要注意规范中包含的示例:
// the declaration of the property
.property int32 Count() {
.get instance int32 MyCount::get_Count()
.set instance void MyCount::set_Count(int32)
.other instance void MyCount::reset_Count()
}
这表明“重置”是一种选择;然而,实际上这是通过反射模式处理的;因此对于:
public int Foo {get;set;}
约定是的public void ResetFoo()
重置方法Foo
,但编译器不会将其处理为自定义访问器。
using System;
using System.ComponentModel;
public class MyType
{
public int Foo { get; set; }
public void ResetFoo() { Foo = 0; }
static void Main()
{
var obj = new MyType {Foo = 123};
TypeDescriptor.GetProperties(typeof(MyType))["Foo"].ResetValue(obj);
Console.WriteLine(obj.Foo); // outputs: 0
var accessors = typeof (MyType).GetProperty("Foo").GetAccessors();
// writes get_Foo and set_Foo
foreach(var acc in accessors) Console.WriteLine(acc.Name);
}
}