• C# 属性、索引


    属性(property: 

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }    

    简写为:

    public string Name { set; get;}

     

    索引器(index):

    索引器为C#程序语言中泪的一种成员,它是的对象可以像数组一样被索引,使程序看起来更直观,更容易编写。

    索引器和数组比较:

    (1)索引器的索引值(Index)类型不受限制

    (2)索引器允许重载

    (3)索引器不是一个变量

    索引器和属性的不同点

    (1)属性以名称来标识,索引器以函数形式标识

    (2)索引器可以被重载,属性不可以

    (3)索引器不能声明为static,属性可以

    要声明类或结构上的索引器,请使用this关键字,例如: 

    public int this[int index] //声明索引器
    
    {
    
    // get and set 访问
    
    }

     索引器的修饰符有:new、public、protected、internal、private、virtual、sealed、override、abstract和extern。

     

    当索引器声明包含extern修饰符时,称该索引器为外部索引器。因为外部索引器声明不提供任何实际的实现,所以它的每个访问器声明都由一个分号组成。

     

    索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。

    索引器值不归类为变量;因此,不能将索引器值作为ref或out参数来传递。

     

    索引必须是实例成员。

    索引器使用示例:

    using System;
    class IndexerRecord
    {
        private string [] data = new string [6];
        private string [] keys  = {
            "Author", "Publisher", "Title",
            "Subject", "ISBN", "Comments" 
            }; 
         
        //注:程序中用了两种方法来索引:
        //一是整数作下标,二是字符串(关键词名)作下标
        public string this[ int idx ]
        {
            set
            {
                if( idx >= 0 && idx < data.Length )
                    data[ idx ] = value;
            }
            get
            {
                if( idx >= 0 && idx < data.Length )
                    return data[ idx ];
                return null;
            }
        }
        public string this[ string key ]
        {
            set
            {
                int idx = FindKey( key );
                this[ idx ] = value;
            }
            get
            {
                return this[ FindKey(key) ];
            }
        }
        private int FindKey( string key )
        {
            for( int i=0; i<keys.Length; i++)
                if( keys[i] == key ) return i;
            return -1;
        }
        static void Main()
        {
            IndexerRecord record = new IndexerRecord();
            record[ 0 ] = "马克-吐温";
            record[ 1 ] = "Crox出版公司";
            record[ 2 ] = "汤姆-索亚历险记";
            Console.WriteLine( record[ "Title" ] );
            Console.WriteLine( record[ "Author" ] );
            Console.WriteLine( record[ "Publisher" ] );
            
            Console.ReadKey(true);
        }
    }
  • 相关阅读:
    RESTful Web服务的操作
    Nginx学习之如何搭建文件防盗链服务
    PostgreSQL10.5安装详细步骤(Win10)
    前端安全系列(一):如何防止XSS攻击?
    【原码笔记】-- protobuf.js 与 Long.js
    【微信开发】-- 发送模板消息
    能编程与会编程
    vue2入坑随记(二) -- 自定义动态组件
    微信上传图片
    vue2入坑随记(一)-- 初始全家桶
  • 原文地址:https://www.cnblogs.com/bincoding/p/4870002.html
Copyright © 2020-2023  润新知