3

我正在反思一种类型的属性,并想检查一个属性是否同时具有公共setter 和 getter。不幸的是,PropertyInfo's CanReadandCanWrite并不表示可访问性级别。所以我转向了PropertyInfo.GetAccessors()其中有一个有趣的描述(强调我的):

返回一个数组,其元素反映当前实例所反映的属性的公共 get、set 和其他访问器。

有哪些“其他访问者”?是否仅存在其他访问器的可能性,或者是否存在实际上具有比属性的简单设置/获取二重奏更多的 CLI 语言?

4

2 回答 2

5

实际上,只有一个 getter 和 setter。从技术上讲,IIRC CLI 规范(ECMA 335 第 1.8.11.3 节)不仅限于这些,因此其他一些语言可以自由添加其他含义,但实际上没有。

这显示在 table 中II.17,并使用.otherIL 中的标题(注意它.get用于 getter、.setsetter 和.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);
    }
}
于 2012-07-26T11:30:53.637 回答
1

事件具有注册代表addremove访问器(这就是+=被翻译成的内容)。

编辑:好的,它们与属性无关,但它们属于“其他访问器”的类别。EventInfo,有趣的是,只有方法GetAddMethodGetRemoveMethod。此外,还有GetOtherMethodand GetRaiseMethod,但那是我不太了解的黑暗魔法......

于 2012-07-26T11:30:27.863 回答