为什么抛出异常?

时间:2012-08-02 18:17:35

标签: asp.net asp.net-mvc-3

我有一个基本控制器:

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 个答案:

答案 0 :(得分:1)

您需要为InjuredWorkerController提取一个界面才能使其正常工作,因为共同和逆变只适用于接口和代理。

这段代码编译并运行(C#console app,我不熟悉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必须阅读。