【问题标题】:implicit conversion from generic interface type [duplicate]从通用接口类型的隐式转换[重复]
【发布时间】:2013-07-29 18:02:33
【问题描述】:

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

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 的原因可能是什么?

【问题讨论】:

  • 这个工作:InputArgument input = (IPrinciple) User; ?
  • 不行,试过了,同样的错误。
  • implicit operator using interfaces 的可能重复项 - 该问题给出了“它在语言规范中”的原因,但并没有真正解释原因。 The question it links to 更深入一点。
  • 你能分享一下定义 InputArgument 类的代码吗?您使用的是哪个版本的 .NET Framework?
  • 糟糕,我没有做好搜索工作。

标签: c# implicit-conversion


【解决方案1】:

用户定义的转换被指定为在接口上起作用。如果他们确实在这样的接口上工作,那么您最终可能会遇到Bar&lt;IFoo&gt; 通过更改表示的用户定义转换转换为IFoo 当对象实际实现时 IFoo ,这将是令人惊讶的。

【讨论】:

    猜你喜欢
    • 2014-11-06
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2014-06-12
    相关资源
    最近更新 更多