论坛首页 编程语言技术论坛

.net 索引器

浏览 1397 次
锁定老帖子 主题:.net 索引器
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-02-06  
    [url].net
[/url]http://www.ixueyun.com/lessons/detail-lessonId-518.html
    public class Example
    {
        public Int32 _str;

        //定义一个索引器
        public Int32 this[Boolean b] {
            get { return _str; }
            set { _str = value; }
        }
    }
一个类型可以有多个索引器,如下:
    public class Example
    {
        public Int32 _int;

        //定义一个索引器
        public Int32 this[Boolean b]
        {
            get { return _int; }
            set { _int = value; }
        }

        //定义另一个索引器
        public String _str = "example";
        public String this[Int32 index]
        {
            get { return _str; }
            set { _str = value; }
        }
    }
当一个类型存在多个索引器,如果说要在不同的编程语言间进行操作时,可以为索引器指定名称,方式如下:
利用System.Runtime.CompilerServices; 中的[IndexerName("name")]特性来完成。
以上面的代码为例:
    public class Example
    {
        //定义一个索引器
        public Int32 _int;
        [IndexerName("IntIndexer")]
        public Int32 this[Boolean b]
        {
            get { return _int; }
            set { _int = value; }
        }

        //定义另一个索引器
        public String _str = "example";
        [IndexerName("StringIndexer")]
        public String this[Int32 index]
        {
            get { return _str; }
            set { _str = value; }
        }
    }
c#对索引器的限制会导致以下的问题:如果其它语言的开发人员在一个类型中定义了多个不同名称的含参属性,那么c#如何使用该类?答案是该类型必须选择一个含参属性作为默认的属性。这可以通过System.Reflection.DefaultMemberAttribute来实现。
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics