Code: Select all
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>
Kann mein Code zur Laufzeit tatsächlich fehlschlagen, da ich den Typ überprüfe und nur implizit gießt, wenn der Typ korrekt ist? Oder ist der C# Compiler nicht klug genug, um zu sehen, dass ich vor den Typen geschützt habe?