クラスからインターフェイスへの無効なキャストを試みても、コンパイラは文句を言いません(エラーは実行時に発生します)。ただし、抽象クラスと同様のキャストを試してみると、文句を言います。
class Program
{
abstract class aBaz
{
public abstract int A { get; }
}
interface IBar
{
int B { get; }
}
class Foo
{
public int C { get; }
}
static void Main()
{
Foo foo = new Foo();
// compiler error, as expected, since Foo doesn't inherit aBaz
aBaz baz = (aBaz)foo;
// no compiler error, even though Foo doesn't implement IBar
IBar bar = (IBar)foo;
}
}
(一見?)無効なのに、コンパイラがFooからIBarへのキャストを拒否しないのはなぜですか?または、質問を裏返すと、コンパイラがこの「無効な」キャストをインターフェイスIBarに許可する場合、抽象クラスaBazへの同様の「無効な」キャストを許可しないのはなぜですか。