从泛型接口类型的隐式转换

本文关键字:转换 泛型 接口类型 | 更新日期: 2023-09-27 18:25:19

我有以下隐式转换运算符:

public static implicit operator InputArgument<T>(T value)
{
   return new InputArgument<T>(value);
}

以下是ASP.NET MVC控制器中的代码:

这项工作:

InputArgument<string> input = "Something";

这项工作:

InputArgument<Controller> input = this;

这项工作:

InputArgument<IPrincipal> input = new InputArgument<IPrincipal>(User);

但这不起作用:

InputArgument<IPrincipal> input = User;

最后一个例子给出了错误:

> Cannot implicitly convert type
> 'System.Security.Principal.IPrincipal' to
> 'Engine.InputArgument<System.Security.Principal.IPrincipal>'. An
> explicit conversion exists (are you missing a cast?)

这种隐式转换不适用于IPrincipal的原因是什么?

从泛型接口类型的隐式转换

用户定义的转换被指定为而不是处理接口。如果他们确实在这样的接口上工作,那么当对象实际实现IFoo时,Bar<IFoo>可能会通过一个改变表示的用户定义转换转换为IFoo,这将是令人惊讶的。