您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

如何重载 C# 中的运算符?

2025/5/9 17:37:10发布27次查看
[] 运算符被称为索引器。
索引器允许对对象进行索引,例如数组。当您为一个类定义一个索引器时,该类的行为类似于一个虚拟数组。然后,您可以使用数组访问运算符([ ])访问该类的实例。
索引器可以被重载。索引器也可以声明多个参数,并且每个参数可以是不同的类型。索引不一定必须是整数。
示例1static void main(string[] args){ indexerclass team = new indexerclass(); team[0] = "a"; team[1] = "b"; team[2] = "c"; team[3] = "d"; team[4] = "e"; team[5] = "f"; team[6] = "g"; team[7] = "h"; team[8] = "i"; team[9] = "j"; for (int i = 0; i < 10; i++){ console.writeline(team[i]); } console.readline();}class indexerclass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set { names[i] = value; } }}
输出abcdefghij
example 2重写 []static class program{ static void main(string[] args){ indexerclass team = new indexerclass(); team[0] = "a"; team[1] = "b"; team[2] = "c"; for (int i = 0; i < 10; i++){ console.writeline(team[i]); } system.console.writeline(team["c"]); console.readline(); }}class indexerclass{ private string[] names = new string[10]; public string this[int i]{ get{ return names[i]; } set{ names[i] = value; } } public string this[string i]{ get{ return names.where(x => x == i).firstordefault(); } }}
输出abcc
以上就是如何重载 c# 中的运算符?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product