【发布时间】:2011-01-31 14:20:13
【问题描述】:
最近我遇到了与演员表相关的奇怪问题。我看到的每一个讨论/帖子都倾向于围绕使用铸造,当一个人确定被铸造的对象加上几个细节时。但是我还没有找到下面代码背后的原因:
class Program
{
static void Main(string[] args)
{
var h = new SomeCommandHandler();
var c = h as ICommandHandler<ICommand>; //this works as expected
//var c = (ICommandHandler<ICommand>)h; //this throws - why?
}
interface ICommand { }
class SomeCommand : ICommand { }
interface ICommandHandler<I> where I : ICommand { }
class SomeCommandHandler : ICommandHandler<SomeCommand> { }
}
那么为什么第二次调用会抛出异常呢?我不知道的 cast 和 as 运算符有什么区别?
编辑: 它会在上面的注释行中抛出 “未处理的异常:System.InvalidCastException:无法将 'SomeCommandHandler' 类型的对象转换为类型 'ICommandHandler`1[ConsoleApplication1.Program+ICommand]'”
【问题讨论】:
-
@thecoop - 冒险猜测它是一个 InvalidCastException...