白羽
2018-07-10
来源 :网络
阅读 1771
评论 0
摘要:本文将带你了解C#编程之索引器初识,希望本文对大家学C#/.Net有所帮助。
c#提供了索引器进行访问的方法。
定义索引器的方法:
public string this[int index]//权限 类型 this指针是必须的后面是参数
来个例子:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
family f = new family();
f[1] = "四毛";
Console.WriteLine(f[2]);
Console.WriteLine(f[1]);
}
class family
{
private string child1 = "大毛";
private string child2 = "二毛";
private string child3 = "三毛";
public string this[int index]
{
//在编译的时候把get和set给编译成了两个方法
get
{
if (index == 0)
{
return child1;
}
if (index == 1)
{
return child2;
}
if (index == 2)
{
return child3;
}
throw new Exception("参数错误");
}
set
{
if (index == 0)
{
child1 = value;
}
else
if (index == 1)
{
child2 = value;
}
else
if (index == 3)
{
child3 = value;
}
else
{
throw new Exception("参数错误");
}
}
}
}
}
}
运行结果:
索引器定义:string this[int index]{get{return "";}set{}},
string是索引器的类型,[]里面是参数列表,进行索引器写操作就是调用set代码块,在set内部使用value得到用户设置的值,进行读操作就执行get代码块。
类型:
程序员说要有索引器,于是就有了索引器。索引器的参数当然可以不止一个,类型也不限于int,几乎可以是任意类型。
索引器的本质:
反编译之。
最简单的索引器使用:
string s = "aaa";char ch = s[0];
这种赋值方法你以为是新语法??
以上就介绍了C#.NET的相关知识,希望对C#.NET有兴趣的朋友有所帮助。了解更多内容,请关注职坐标编程语言C#.NET频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号