C# 属性 索引

一 使用属性、索引的示例

1 使用属性button1.Text

① button1.Text=“说你好”;
含义相当于button1.SetText(“说你好”);
② string s=button1.Text;

2 使用属性string s=“abcde”

① 求出长度:s.Length;
含义上相当于s.GetLength();

3 使用索引 string s=“abcde”;

① 求出第0个字符:s[0]
含义上相当于s.Get(0);

二 属性(property)的书写

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

注意:
在C# 3.0以上版中可简写为

public string Name{set;get;}

1 对属性进行访问

Person p=new Person();
p.Name="Li Ming";
Console.WriteLine(p.Name);

编译器产生的方法是

void set_Name(string value);
string get_Name();

2 属性与字段的比较

由于属性实际上是方法,所以属性可以具有优点:
① 可以只读或只写:只有get或set;
② 可以进行有效性检查:if…;
③ 可以是计算得到的数据:

public string Info
{
   get{return "Name:"+Name+",Age:"+Age;}
}

可以定义抽象属性;

3 索引器(indexer)

修饰符 类型名 this[参数列表]
{
set{}
get{}
}

4 使用索引

对象名[参数]

编译器自动产两个方法,以供调用:
T get_Item§;
void set_Item(P,T value);

5 属性与索引的比较

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 索引记录
{
    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();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值