2012-08-02 259 views
0

我有一個基本的控制器:爲什麼這會拋出異常?

Public MustInherit Class InjuredWorkerController(Of TManager As IInjuredWorkerManagerBase) 

然後,我有一個家居控制器:

Public Class HomeController 
    Inherits InjuredWorkerController(Of IInjuredWorkerManager) 

IInjuredWorkerManager繼承IInjuredWorkerManagerBase

爲什麼這個拋出一個轉換異常:

Dim manager = CType(filterContext.Controller, InjuredWorkerController(Of IInjuredWorkerManagerBase)).Manager 

無法將'MyClaim.Controllers.HomeController'類型的對象轉換成'MyClaim.Controllers.InjuredWorkerController`1 [SAIF.Web.Mvc.MyClaim.IInjuredWorkerManagerBase]'。

+1

泛型在.NET中沒有共同/反差。 – 2012-08-02 18:22:11

+0

實際上,它們只能在4.0版本中使用,而且只能用於接口 - 而且必須指定您希望自己的接口擁有它們。 – ekolis 2012-08-02 18:28:59

+0

@ekolis - 你能指點我的文檔嗎? – Sam 2012-08-02 18:43:12

回答

1

您需要爲您的InjuredWorkerController提取一個接口才能使其工作,因爲協同和逆變僅適用於接口和委託。

此代碼可以編譯和運行(C#控制檯應用程序,我不精通VB.Net ...):

using System; 

namespace TestApplication 
{ 
    public interface IInjuredWorkerController<out TManager> 
     where TManager : IInjuredWorkerManagerBase 
    { 
     TManager Manager { get; } 
    } 

    public abstract class InjuredWorkerController<TManager> 
     : IInjuredWorkerController<TManager> 
     where TManager : IInjuredWorkerManagerBase, new() 
    { 
     protected InjuredWorkerController() 
     { 
      Manager = new TManager(); 
     } 

     public TManager Manager { get; private set; } 
    } 

    public interface IInjuredWorkerManagerBase 
    { 
     string Name { get; } 
    } 

    public interface IInjuredWorkerManager 
     : IInjuredWorkerManagerBase {} 

    public class InjuredWorkerManager : IInjuredWorkerManager 
    { 
     public string Name 
     { 
      get { return "Homer"; } 
     } 
    } 

    public class HomeController 
     : InjuredWorkerController<InjuredWorkerManager> {} 

    internal class Program 
    { 
     private static void Main() 
     { 
      var controller = new HomeController(); 
      var manager = ((IInjuredWorkerController<IInjuredWorkerManagerBase>)controller).Manager; 

      Console.Out.WriteLine(manager.Name); 
      Console.ReadKey(); 
     } 
    } 
} 

Eric Lippert's blog series關於這個問題是一個必須閱讀。

+0

謝謝TON!奇蹟般有效! – Sam 2012-08-02 22:15:07

相關問題