Fil*_*ada 0 c# generics casting
最近我遇到了与铸造有关的奇怪问题.我所看到的每一个讨论/帖子都倾向于围绕使用强制转换,当确定要渲染的对象加上一些细节时.然而,我没有找到下面代码背后的原因:
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> { }
}
Run Code Online (Sandbox Code Playgroud)
那么为什么第二个调用抛出一个异常呢?我不知道铸造和操作员之间的区别是什么?
编辑:它wpuld抛出上面的注释行"Unhandled Exception:System.InvalidCastException:无法将'SomeCommandHandler'类型的对象强制转换为'ICommandHandler`1 [ConsoleApplication1.Program + ICommand]'"