Код: Выделить всё
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
}
// Code with violations.
var list = new List();
foreach (string item in list) { }
// Fixed code.
var list = new List();
foreach (string item in list.Cast())
< /code>
< /blockquote>
Может ли мой код на самом деле не сработал во время выполнения, так как я проверяю тип и неявно, только если тип правильный? Или компилятор C# недостаточно умный, чтобы увидеть, что я охранял от неверных типов?
Подробнее здесь: https://stackoverflow.com/questions/794 ... op-ide0220