《.Net框架程序设计》读书笔记 之 结构和索引器

一:结构和索引器(又称含参属性)
class classStruct
{
    
struct MyStruct
    
{
        
public string[] strTest;
        
public string this[int index]
        
{
            
get
            
{
               
return strTest[index];
            }

            
set
            
{
               strTest[index]
=value;
            }

        }

    }

    
public static void Main()
    
{
        MyStruct ms 
= new MyStruct();
        ms.strTest 
= new string[2];
        ms[
0= "aaaaa";
        ms[
1= "bbbbb";
        Console.WriteLine(
"第一个是{0},第二个是{1}",ms[0],ms[1]);
    }

}

//适用于处理大量相当类型数据,如从数据库中读出一纪录并操作时
1.结构成员声明前要加public关键字
2.不允许在声明结构时初始化结构成员
3.结构中的属性因为并不分配有存储空间,所以不能作为ref或者out参数进行传递
4.结构可以实现接口
类中同样可以有索引器(含参属性)
public class classIndex
{
    
public boolean this[int i]
    
{
        
get{;}
        
set{;}
    }

}

//访问方式为
classIndex ci = new classIndex(5);
ci[
0]
ci[
1]
ci[
2]
ci[
3]
ci[
4]
ci[
5]
//定义了get和set就可以进行取值和赋值操作
//1.C#不允许为索引器指定名称
   自动指定为get_Item  set_Item
//2.System.Runtime.CompilerServices.IndexerNameAttribute可指定索引器名称。但C#中不支持使用名字定位索引器
[System.Runtime.CompilerServices.IndexerName("MyName")]
public boolean this[Int i]
{
   
//此索引器的名字为set_MyName  get_Myname,而不是set_Item  get_Item
}

//System.string是一个改变了名称的索引器,其名称为Chars而不是Item.这样我们可以得到一个字符串中的单个字符
posted on 2005-11-18 13:40  泽来  阅读(373)  评论(0编辑  收藏  举报