我正在尝试使用 Activator.CreateInstance 创建一个类并将其转换为它实现的通用接口。
为什么我在运行时收到“InvalidCastException”(.Net 4.0)?
这是代码:
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
{
}
}