小编Sun*_*y D的帖子

在Unity中使用泛型... InvalidCastException

我的接口定义是:public interface IInterface其中T:UserControl

我的类定义是:public partial class App1Control:UserControl,IInterface

app.config的统一部分如下所示:

  <unity>
    <typeAliases>
      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
      <typeAlias alias="myInterface" type="MyApplication.IInterface`1, MyApplication" />
      <typeAlias alias="App1" type="MyApplication.App1Control, MyApplication" />
    </typeAliases>
    <containers>
      <container> 
        <types>
          <type type="myInterface" mapTo="App1" name="Application 1">
            <lifetime type="singleton"/>
          </type>
        </types>
      </container>
    </containers>
  </unity>
Run Code Online (Sandbox Code Playgroud)

应用程序运行正常但是,以下代码给出了InvalidCastException

container.Resolve<IInterface<UserControl>>("Application 1");
Run Code Online (Sandbox Code Playgroud)

错误消息是:

无法将"MyApplication.App1Control"类型的对象强制转换为"MyApplication.IInterface`1 [System.Windows.Forms.UserControl]"

我相信我的代码中存在一个小错误......但我无法弄清楚是什么.有什么想法吗?

.net generics configuration inversion-of-control unity-container

5
推荐指数
1
解决办法
839
查看次数