C#笔记——属性与索引器

本文最后更新于:2023年11月12日 晚上

属性

写法

示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class ClassName
{
AccessModifier Type _properName;
AccessModifier Type ProperName
{
set
{
// 赋值代码
}
get
{
// 取值代码
}
}
}

所有set访问器都用一个隐藏的,内建的参数(名为value)来传递要写入的数据,比如:this._properName = value
如果是在接口中,那就不需要写方法体了:

1
2
3
4
interface IExampleInterface
{
Type ProperName { get; set; }
}

自动生成

C#编译器现在能自动为属性生成代码:

1
2
3
4
class ClassName
{
public int ProperName { get; set;}
}

但是只能声明只读自动属性,不能声明只写自动属性。

用属性初始化对象

现在有这样一个类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ExampleClass
{
private int _a;
private int _b;
private int _c;

public int A
{
set { this._a = value; }
}
public int B
{
set { this._b = value; }
}
public int C
{
set { this._c = value; }
}
}

创建类的时候,可为具有set访问器的任何公共初始属性指定名称和值:

1
2
3
ExampleClass object1 = new ExampleClass { A = 1 };
ExampleClass object1 = new ExampleClass { A = 1, B = 2 };
ExampleClass object1 = new ExampleClass { A = 1, B = 2, C = 3 };

先运行构造器,再对属性进行设置

索引器

索引器和属性很相似,只不过属性封装的是类中的一个值(字段),而索引器封装的是一组值(数组)。

自我感觉很棒的例子

有时候我们会将int类型的一个变量来作为二进制标志集合使用,但是操作和可读性上不会太好,比如bits &= ~(1 << 5)或是bits |= (1 << 5),我们或许想要这么干:bits[5] = true,那么这个时候索引器就派上用场了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
struct IntBits
{
private int bits;
public IntBits(int initialBitValue)
{
bits = initialBitValue;
}
public bool this [ int index ]
{
get
{
return (bits & (1 << index)) != 0;
}

set
{
if (value) // 如果value为true,就将指定的位设为1;否则设为0
bits |= (1 << index);
else
bits &= ~(1 <<index);
}
}
}

这个时候,就能使用上面提到的访问数组的方式来访问int变量的每一位了:

1
2
3
4
int x = 126;
IntBits bits = new IntBits(x);
bool peek = bits[6]; // 获取索引6的bool值
bits[0] = true; // 将索引0的位设为1

这里有一只爱丽丝

希望本文章能够帮到您~


C#笔记——属性与索引器
https://map1e-g.github.io/2023/08/15/CSharp-learning-3/
作者
MaP1e-G
发布于
2023年8月15日
许可协议