我正在尝试使用Activator.CreateInstance创建一个类,并将其转换为它实现的通用接口。

为什么在运行时(.Net 4.0)收到“ InvalidCastException”?

这是代码:

namespace CastingGenerics
{
    class Program
    {
        static void Main(string[] args)
        {
            var typeFromSomewhere = typeof(ActionSomethingValidator);

            // This line throw 'System.InvalidCastException'
            // "Unable to cast object of type 'CastingGenerics.ActionSomethingValidator' to type 'CastingGenerics.IActionValidator`1[CastingGenerics.IAction]'."
            var castingError = (IActionValidator<IAction>)Activator.CreateInstance(typeFromSomewhere);
        }
    }

    internal interface IAction
    {
    }

    internal interface IActionValidator<in T>
        where T : IAction
    {
        bool Validate(T action, out string failure);
    }

    internal abstract class ActionValidator<T> : IActionValidator<T>
        where T : IAction
    {
        public abstract bool Validate(T action, out string failure);
    }

    internal class ActionSomethingValidator : ActionValidator<IActionSomething>
    {
        public override bool Validate(IActionSomething action, out string failure)
        {
            failure = string.Empty;
            return true;
        }
    }

    internal interface IActionSomething : IAction
    {
    }
}

最佳答案

您得到的是一个IActionValidator<IActionSomething>。无法将IActionValidator<IActionSomething>分配给IActionValidator<IAction>,因为T被标记为in类型参数。

想象一下,对于名为IActionValidator<IAction>v变量,有以下Validate方法:

Validate(IAction action, out string failure);


现在,如果v指向IActionValidator<IActionSomething>的实例,则可以通过未实现IActionvIActionSomething实例传递给第一个参数。但是,IActionValidator<IActionSomething>完全需要后者。因此,编译器将不允许您执行此操作。

10-08 14:00