【发布时间】:2013-05-20 15:52:11
【问题描述】:
方法 Array.SetValue(Object value, int index) 允许涉及值/数组类型对的赋值,这通常允许使用通用索引器语法,并在您尝试组合通常不允许的类型时抛出异常.例如,考虑以下局部变量声明:
int[] twoints = new int[2] { 5, 6 };
以下四行不会引发任何运行时或编译时异常:
twoints[1] = (sbyte)7;
twoints.SetValue((sbyte)7, 1);
twoints[1] = (char)7;
twoints.SetValue((char)7, 1);
另一方面,这四行中的每一行都会在运行时或设计时抛出异常:
twoints[1] = 4.5;
twoints.SetValue(4.5, 1);
twoints[1] = 4L;
twoints.SetValue(4L, 1);
但是,当我将字节值分配给 char 数组时,我得到了奇怪的结果。编译时拒绝索引器语法,运行时调用SetValue的API成功:
char[] twochars = new char[2] { 'A', 'B' };
twochars[1] = (byte)70; // Not OK, refused by the compiler
twochars.SetValue((byte)70, 1); // OK, no exception at run-time
为什么允许这个操作?
【问题讨论】:
标签: c# arrays type-conversion