07 C# 索引器 分部类

创建一个索引器示例:

class MyDemoCls

{

int temp0;

int temp1;//2个私有字段

public int this[int index]//索引

{

get

{

return (0 == index) ? temp0 : temp1;

}

set

{

if (0 == index)

temp0 = value;

else

temp1 = value;

}

}

}

测试类的索引器:

class Program

{

static void Main(string[] args)

{

MyDemoCls myCls = new MyDemoCls();

Console.WriteLine($“Values --To,T0:{myCls[0]},T1:{myCls[1]}”);

myCls[0] = 15;

myCls[1] = 20;

Console.WriteLine($“Values --To,T0:{myCls[0]},T1:{myCls[1]}”);

}

}

输出:

Values --To,T0:0,T1:0

Values --To,T0:15,T1:20

索引器重载

只要索引器的参数列表不同,类就可以有任意多个索引器。

类中重载索引器必须有不同的参数列表。索引器都使用相同的名字this访问引用。

访问器的访问修饰符

默认访问级别一致的,可为2个访问器设置不同的访问级别。

public string Name{ get; private set;}

分部类和分部类型

类的声明可以分割成几个分部类的声明。

每个分部类声明必须被标注partial class,而不是独立的关键字 class

组成分部类的所有分布类声明必须在一起编译

分部方法

分部方法是声明在分布类中不同部分的方法。

partial class myClass

{

partial void PrintNumber(int x, int y);// 定义分部方法

public void Add(int x, int y)

{

PrintNumber(x, y);

}

}

partial class myClass

{

partial void PrintNumber(int x, int y)// 实现代码部分

{

Console.WriteLine($“Sum is {x+y}”);

}

}

测试分部类:

class Program

{

static void Main(string[] args)

{

myClass cls = new myClass();

cls.Add(5, 10);

}

}

输出:

Sum is 15

上一篇:神经网络与误差反向传播


下一篇:电磁场与电磁波(一)