作为我问题的简化示例,我有一个数组
ISomeType
,我想循环浏览实际上是该数组中的所有元素,但是我得到了IDE0220警告”明确施放foreach循环“我认为不适用。这是一个代码示例:
MyType
编译器抱怨它隐式地将元素施加到public interface ISomeType {
void DoThing();
}
public class MyType: ISomeType {
void DoThing() { /* do something */ }
void DoMyTypeThing() { /* do something specific to MyType */ }
}
public class YourType: ISomeType {
void DoThing() { /* do something */ }
void DoMyTypeThing() { /* do something specific to MyType */ }
}
ISomeType[] maybeMyTypes = [new MyType()];
// I get the error on this line because I cast the element into `MyType`
foreach (MyType foobar in maybeMyTypes.Where(i => i.GetType() == typeof(MyType))) {
// use the MyType methods availbale on foobar
}
中,并且在运行时可能会失败,因此我应该明确有关演员表:
maybeFooBars
我的代码实际上会在运行时失败,因为我正在检查类型,并且仅在类型正确的情况下隐式施放?还是C#编译器不够聪明,无法看到我防御了不正确的类型?MyType