日期:2014-05-18  浏览次数:20853 次

菜鸟提问,高手帮忙 请问这段程序讲的是什么意思!
我对索引器不太明白,象程序里的set和get等起什么作用,高手能给详细讲讲吗,谢谢.
程序如下:
using System;

namespace PropertyIndexerApp
{
class Class1
{
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;
}
}
}
}

------解决方案--------------------
索引器就是给类提供了一种好像数组的操作方式
------解决方案--------------------
属性如果是数组的话就就叫索引器,我是这么理解的
------解决方案--------------------
可以像四楼 那么 理解 ,
索引器名字 永远是 this访问的时候 也不用打属性名。
比如 A类中 声明了一个
public string this[string key]
{
get{;}
set{;}
}
我们 声明一个 A类的 对象。
A test=new A();
直接 要访问 索引器 :test["a"]就可以了

get块 就是 访问 块,当 我们 调用 索引器时 ,就会执行这个 块 ,最后 这个块返回一个 值 供用户使用。
set块 就是 给 索引器 赋值时 要执行的块 。
新值 在 叫做 value的 变量里 ,在这里 可以 操作 。
这个这是 一个 通向外部 和 操作内部 的 一个 方法 ,并没有 储存 真实信息 。这个和属性 时一样的。