class ArrayVariance
{
static void Main()
{
string[] strings = new string[5];
object[] objects = strings;
objects[0] = new object();
}
}
运行会引起 ArrayTypeMismatchException: 异常
因为 string[] 转换 成 object[] 会返回初始引用 strings 和 objects都引用同一个数组
数组知道是一个 字符串,会拒绝非 字符串的引用
数组是强类型的,在编译时,不可能将string[] 的一个元素设置成FileStream
引用类型支持协变, 只要元素的类型之间允许这样的转换,就能隐式将一个 数组类型转换成另一种类型
输出
Exception: System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.ArrayTypeMismatchException: 试图访问类型与数组不兼容的元素。
在 Chapter02.ArrayVariance.Main() 位置 c:\Users\Adminstrator\Desktop\深入理解C# 第三版 源代码\C# in Depth\OtherChapters\Chapter02\ArrayVariance.cs:行号 12
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
在 MiscUtil.ApplicationChooser.Run(Type type, String[] args)