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]”。

4

1 回答 1

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关于这个主题的博客系列是必读的。

于 2012-08-02T19:13:33.070 回答