我有以下简短的C#程序:
IList<string> listString = new List<String>();
IList<object> listObject;
listObject = listString;
Run Code Online (Sandbox Code Playgroud)
这个程序不编译.最后一行导致以下编译错误:
无法将类型'System.Collections.Generic.IList'隐式转换为'System.Collections.Generic.IList'.存在显式转换(您是否错过了演员?)
所以,我添加了演员:
listObject = (IList<object>)listString;
Run Code Online (Sandbox Code Playgroud)
现在程序正确编译,但在运行时失败.的InvalidCastException升高与以下消息:
无法将类型为'System.Collections.Generic.List'1 [System.String]'的对象强制转换为'System.Collections.Generic.IList'1 [System.Object]'.
强制转换是非法的,应该被编译器捕获,或者它是合法的,不应该在运行时抛出异常.为什么行为不一致?
澄清:我不是在问为什么演员会失败.我明白为什么这样的铸造有问题.我问为什么演员阵容只在运行时失败.