C# 接口 索引 属性 实质及应用 (收集)

接口实际上是一种标准,我们知道如果一个类继承于这个接口,那么就要给出接口里方法的实现,
实际上就是要求这个类要遵守这个标准。实际作用是,比如我们有某一个操作,我们想让这个操作对不同的类都能使用,
但各个类内部结构不同,要实现这个操作,可能会有细微的差别,所以我们通过让各个类继承于某一个接口,
也就找到了他们共同的遵守标准,然后我们就可以在这样的前提下,通过接口来操作各个类,来完成所说的那个操作了 

 

1、索引符是一种特殊类型的属性,可以把它添加到一个类中,以提供类似数组的访问。实际上索引的实质就是利用list的可以按下标访问的特性,
比方:public class Animal:CollectionBase{ ……………… public Animal this[int animalIndex] {  get  {return (Animal)List[animalIndex];
//IList.List属性返回一个System.Object对象,所以要显式转换  }  set  {   List[animalIndex] = value;  } }}2、接口其实跟函数的重载差不多,
只不过被重载函数有实现,而接口没有实现,并且只能依赖类实现。实际上接口跟函数声明差不多,给出接口名和需要的形参,实际上的实现就可以由继承类自己写。
3、属性主要用于保护数据的安全,在C++中private数据只能通过公共函数操作,保护级别太高,有些时候不用这么复杂,因此在C#中推出了属性,
可以通过公共属性操作私有数据,通过设置其中的get和set可以使私有数据只读,或者可读可写 

 

 

//存放Vector实例
InBlock.gif        private List<Vector> _vectors;
InBlock.gif
InBlock.gif        public List<Vector> Vectors
ExpandedSubBlockStart.gif        {
InBlock.gif            get
ExpandedSubBlockStart.gif            {
InBlock.gif                if (null == _vectors)
ExpandedSubBlockStart.gif                {
InBlock.gif                    _vectors = new List<Vector>();
ExpandedSubBlockEnd.gif                }

InBlock.gif                return _vectors;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gif        /// <summary>
InBlock.gif        /// 返回或者设置第index条向量
InBlock.gif        /// </summary>
InBlock.gif        /// <param name="index">索引</param>
ExpandedSubBlockEnd.gif        /// <returns></returns> 

InBlock.gif        public Vector this[int index]
ExpandedSubBlockStart.gif        {
InBlock.gif            get
ExpandedSubBlockStart.gif            {
InBlock.gif                return _vectors[index];
ExpandedSubBlockEnd.gif            }

InBlock.gif            set
ExpandedSubBlockStart.gif            {
InBlock.gif                _vectors[index] = value;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif

转载于:https://www.cnblogs.com/zhegebucuo/archive/2010/08/03/1791183.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值