首页 > 开发 > .Net > 正文

第十章 属性[《.net框架程序设计》读书笔记]

2020-02-03 15:56:58
字体:
来源:转载
供稿:网友
第十章 属性

摘要:

本章讨论c#中的 属性 及 索引器

一、属性

分为静态属性、实例属性和虚属性

l 避免直接访问类型字段或使用烦琐的访问器方法进行访问

l 很好的实现了类型的数据封装,如:改变字段而维持属性的意义对用户是透明的

l 代码量小,运算量小的操作才使用属性,否则使用方法调用更合适



二、索引器

l 可有多个重载的索引器,只要参数列表不同即可

l 可通过应用system.runtime.compilerservices.indexernameattribute特性改变编译器为索引器生成的方法名(缺省使用get_item(…),set_item(...))

l 不能通过上述改变方法名的办法来定义多个参数列相同而仅名称不同的索引器

l 没有所谓“静态索引器”



注:在属性或索引器中添加对参数或value值得判定有助于保证程序的完整性



一个简单的示例:

using system;

class indexertest

{

private static string[] strarr = new string[5];



indexertest()

{

for(int i = 0; i < 5; i ++)

{

strarr[i] = i.tostring();

}

}



public string this[int32 nindex]

{

get{

return strarr[nindex];

}



set{

strarr[nindex] = value;

}

}



//提供不同的参数列进行重载索引器

public string this[byte bindex]

{

get{

return strarr[bindex];

}



set{

strarr[bindex] = (string)value;

}

}



//只读属性

public string[] strarr

{

get{

return strarr;

}

}



public static void main()

{

indexertest it = new indexertest();



it[1] = "hello"; //利用索引器进行写操作

foreach(string str in it.strarr)

{

console.writeline(str);

}

}

}

/*

运行结果:

0

hello

2

3

4

*/
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表