C#属性与索引器

using System;

namespace PropertyIndexerApp
{

class Class1
{

[STAThread]
static void Main(string[] args)
{

//创建一个MyClass实例
MyClass m = new MyClass ();

for (int i=0;i<10;i++)
{
for (int j=0;j<10;j++)
{
//写、读第一个索引器
m[i*10,j]=i*10+j;
Console.Write("No{0}{1}:{2}",i,j,m[i*10,j]);
}
Console.WriteLine ();
}

for (int i=0;i<m.StrCount ;i++)
{ //读第二个索引器
Console.WriteLine (m[i]);
}

//Set实例属性
m.StrCount = 5;
//Get实例属性
for (int i=0;i<m.StrCount ;i++)
{ //读第二个索引器
Console.WriteLine (m[i]);
}

//读静态属性
Console.WriteLine (MyClass.ClassName );
Console.Write ("Press any key to continue");
Console.ReadLine ();
}
}

class MyClass
{
private const int c_count = 100;
private static int[] intArray = new int[c_count];
//第一个索引器,可读可写,有两个参数
public int this[int index,int offset]
{
get
{
if ((index+offset)>=0&&(index+offset)<c_count)
{
return intArray[index+offset];
}else return 0;
}
set
{
if ((index+offset)>=0&&(index+offset)<c_count)
intArray[index+offset]=value;
}
}
private int m_strCount = 3;
private string[] strArray = {"111","222","333"};
//第二个索引器,只读,一个参数
public string this[int index]
{
get
{
if ((index>=0)&&(index<m_strCount))
{
return strArray[index];
}
else
{
return "NULL";
}
}
}

//实例属性,可读可写
public int StrCount
{
get
{
return m_strCount;
}
set
{
if (value>m_strCount)
{
strArray = new string[value];
for (int i=0;i<value;i++)
{
strArray[i] = String.Format("String No.{0}",i);
}
m_strCount = value;
}
}
}

private static string m_strName = "MyClass";
//一个静态属性,只读
public static string ClassName
{
get
{
return m_strName;
}
}
}
}


定义:在c#中,属性是类的一种数据结构,它是读写类中私有和受保护的数据的一种途径。属性的读写通过Get和Set访问器进行。类的索引器与属性功能类似,它可以把类虚拟为一个数组,可以按照数组的方式对类的数据进行访问,从而实现对数据的保护和隐藏。索引器的读写也是通过Get和Set访问进行,但它们需要参数。

分析:1。索引器的声明格式为索引器值类型加this关键字,再加数组下标格式的参数。可以在同一个类中定义多个索引器,但是需要它们的参数数量及参数类型不完全相同。因此索引器可以重载,从而接受不同类型的参数,返回不同的类型。

2。索引器在get和set语句中完成数据操作,利用索引器中的参数,对类中的私有成员进行读写。在set语句中,使用value代表赋值参数,它的类型与索引器的类型相同。索引器成员的访问通过类事例加数组下标格式的参数进行。

3。本例中,类MyClass定义了两个属性。一个是静态属性,可以通过类名加属性名对它进行访问,一个是实例属性,可以通过类的实例加属性名进行访问。

4。索引器只可以在类的实例中使用,不可以声明为静态的。属性既可以是实例的也可以是静态的。

参考资料:

-------------------------------------------------------------------------------------------------------------------------------------------------
数据库优化
数据库教程
数据库实战经验分享博客

百度云下载

评测


原文地址:https://www.cnblogs.com/longle/p/indexandattrib.html