作为我的问题的一个简化示例,我有一个数组ISomeType
,我想循环遍历该数组中所有实际的元素MyType
,但我收到IDE0220 警告“在 foreach 循环中添加显式强制转换”,我认为这不适用。以下是代码示例:
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
编译器抱怨它隐式地将的元素转换为MyType
,并且这可能在运行时失败,所以我应该明确说明转换:
// Code with violations. var list = new List<object>(); foreach (string item in list) { } // Fixed code. var list = new List<object>(); foreach (string item in list.Cast<string>())
我的代码在运行时真的会失败吗?因为我正在检查类型,并且只在类型正确时进行隐式转换?还是 C# 编译器不够聪明,无法看出我已经防范了类型不正确?