C#编译器警告有关foreach循环(IDE0220)中隐性铸件的编译器警告

问题描述 投票:0回答:1

作为我问题的简化示例,我有一个数组

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

不会告诉编译器您只与
c# casting warnings
1个回答
0
投票
成员打交道。为此,您需要

.Where(i => i.GetType() == typeof(MyType))
。所以你会喜欢
MyType
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.