索引器(Indexer):官方说法是一种类成员,它允许类或结构的实例按与数组相同的方式排序,索引器与属性类似,只不过索引器的gei和set访问器方法带有参数,而属性访问器方法不带参数。
个人理解: 索引器是C#的一种语法构造,他可以另你用数组的方式来访问类中的集合。索引器是一种特殊的属性,他可以像属性一样通过get和set访问器的方式来指定其行为,不过要额外带参数从集合中取出或者给予赋值行为。
示例:
public class StringContainer
{
private string[] strings;
private int t = 0;
public StringContainer(params string[] initialString)
{
strings = new string[200];
foreach(string s in initialString)
{
strings[t++] = s;
}
}
public void Add(string str)
{
if(t < strings.Length)
{
strings[t++] = str;
}
}
//开始定义我们的索引器
public string this[int index]
{
get
{
if(index < t)
{
return strings[index];
}
}
set
{
if(index < t)
{
strings[index] = value;
}
}
}
public int Counts()
{
return this.t;
}
}
这里我们看到索引器的定义格式,他是通过关键字 this 来定义索引器的,索引器的语法跟属性十分相似,下面我们再看看如何调用定义好的索引器,他的调用跟属性的使用也十分相似,通过get和set并追加参数来获取信息或者赋予执行动作。
{
StringContainer scon = new StringContainer();
scon.Add("a");
scon.Add("b");
scon.Add("c");
scon.Add("e");
string str = "abcd";
scon[1] = str; // 这边通过索引器的方式将【第二个属性值】为b修改为abcd
for(int i=0; i<scon.Counts();i++)
{
Console.WriteLine("{0}:{1}", i , scon[i]);
}
Console.ReadLine();
}
__________________________________________________________________________________________________
摘一段索引器的妙用: 读取配置文件
{
// Fields
private static SysRead m_SysRead;
// Methods
public static string sValue(string sKey)
{
string sPath = AppDomain.CurrentDomain.BaseDirectory + @"Config";
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
string xmlFile = sPath + @"\Config.Xml";
if (File.Exists(xmlFile))
{
m_SysRead = new SysRead(xmlFile);
if (sKey == "Conn")
{
return m_SysRead.sConnection;
}
return m_SysRead[sKey];
}
//MessageBox.Show("读配置文件失败", "提示", MessageBoxButtons.OK);
return "";
}
}
public class SysRead
{
// Fields
private XmlDocument m_xmlDoc;
private string m_xmlFile;
private static XmlNode m_xmlNode;
// Methods
public SysRead(string sXmlFile)
{
try
{
this.m_xmlFile = sXmlFile;
this.m_xmlDoc = new XmlDocument();
this.m_xmlDoc.Load(this.m_xmlFile);
m_xmlNode = this.m_xmlDoc.SelectSingleNode("Config");
}
catch
{
//MessageBox.Show("配置文件中存在非法字符", "提示", MessageBoxButtons.OK);
}
}
~SysRead()//【布颜书】注意这里用~符号来写也是一种方式噢
{
m_xmlNode = null;
this.m_xmlDoc = null;
}
private static string getConnValue(string sKey)
{
try
{
string[] param = new string[2];
param = sKey.Split(new char[] { '.' });
XmlNodeList nodelist = m_xmlNode.ChildNodes;
foreach (XmlElement xE in nodelist)
{
if (xE.Name == param[0])
{
return xE.GetAttribute(param[1]);
}
}
}
catch
{
return "";
}
return "";
}
// Properties
public string this[string sKey]
{
get
{
return getConnValue(sKey);
}
}
public string sConnection
{
get
{
return ("database=" + this["connect.DataBase"] + "; Server=" + this["connect.ServerIp"] + ";User ID=" + this["connect.Uid"] + ";Password=" + this["connect.Pw"] + ";Persist Security Info=True");
}
}
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步