学习C#将近一个月,自己有时性子急,看书没认真理解,就快速地翻过去,这样很不好,自我检讨后,本想写个泛型的练习,结果想到了接口,然后想到了索引器在接口的使用,后来认真地再看了一遍索引器的内容。
C#的索引器,我认为是给类或结构定义个查找的方法,就想数组有下标一样,索引器就是给实例化的类或结构弄个有内容的下标,方便查找或设置,这内容就是编码人自己的事了。
看这个有设置的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace indexer
{
class Program
{
static void Main(string[] args)
{
indexer i=new indexer();
i[1] = "laier";
Console.Write(i[1]);
}
}
public class indexer {
private string[] name = { "laier1","laier2","laier3" };
public string this[int i]{
get{
return name[i];
}
set {
name[i] = value;
}
}
}
}
自己写的小小测试,输出结果为laier
看下一个测试:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace indexer
{
class Program
{
static void Main(string[] args)
{
indexer i=new indexer();
Console.Write(i["laier1"]);
}
}
public class indexer {
private string[] name = { "laier1","laier2","laier3" };
private int getName(string Aname){
int i=0;
foreach (string n in name) {
if (Aname == n)
{
return i; }
i++;
}
return -1;
} public int this[string Aname]{
get{
return getName(Aname);
}
}
}
}
输出结果为0
接口中的索引器:
public interface ISomeInterface
{
// Indexer declaration:
int this[int index]
{
get;
set;
}
}
颜色不一样,嗯,抄MSDN的。