C# 实现接口的方法避免返回类型进行数据类型转换

今天在看C#的IEnumerator 接口的官方文档,看到在实现IEnumerable接口的GetEnumerator()方法时额外写一个同名同参的方法。感到有些疑惑,为什么要这样写,这样写的好处在哪里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];

for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}

// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}

public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
  • 注:PeopleEnum类实现了IEnumerator接口
  • IEnumerable.GetEnumerator()是显式实现接口成员,必须是默认访问修饰符。

在我实现接口的时候,我通常会直接隐式实现接口成员。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];

for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}

public IEnumerator GetEnumerator()
{
return new PeopleEnum(_people);
}
}
  • C# 要求隐式实现接口成员必须是public

但是这样做隐式实现接口成员在返回类型是可继承或接口,且外部调用时需要使用派生后的扩展的方法就需要进行类型转换。

1
2
3
People people = new People(null);
PeopleEnum enum1 = (PeopleEnum)people.GetEnumerator();
int enumLength = enum1.Length();

而使用官方文档那样写,调用扩展的方法就不需要进行类型转换。

1
2
3
People people = new People(null);
PeopleEnum enum1 = people.GetEnumerator();
int enumLength = enum1.Length();