在C#中,一個函數的可訪問 性不能大於它所在類的可訪問性。函數vijay是公有的,然而它所在的類卻是私有的。因此,這個類對包 含在它內部的函數具有更多的約束。再說一遍,在IL中沒有強加這樣的約束。
a.cs
class zzz
{
public static void Main()
{
yyy a = new yyy();
xxx b = new xxx();
a = b;
b = (xxx) a;
}
}
class yyy
{
}
class xxx : yyy
{
}
a.il
.assembly mukhi {}
.class private auto ansi zzz extends [mscorlib]System.Object
{
.method public hidebysig static void vijay() il managed
{
.entrypoint
.locals (class yyy V_0,class xxx V_1)
newobj instance void yyy::.ctor()
stloc.0
newobj instance void xxx::.ctor()
stloc.1
ldloc.1
stloc.0
ldloc.0
castclass xxx
stloc.1
ret
}
}
.class private auto ansi yyy extends [mscorlib]System.Object
{
}
.class private auto ansi xxx extends yyy
{
.method public hidebysig specialname rtspecialname instance void .ctor() il managed
{
ldarg.0
call instance void yyy::.ctor ()
ret
}
}
如果在xxx中沒有構造函數,那麼就會拋出下列異常:
Output
Exception occurred: System.InvalidCastException: An exception of type System.InvalidCastException was thrown.
at zzz.vijay()