c# - 接口(interface)、泛型和隐式操作

标签 c# generics interface implicit-conversion

假设我有这些类型:

public class Foo<T>
{
    public Foo(T value)
    {
         Value = value;
    }

    public T Value {get;set;}

    public static implicit operator Foo<T>(T t)
    {
        return new Foo<T>(t);
    }
}

public interface IBar
{
}

public class Bar : IBar
{
}

为什么不允许我写这个?

Foo<IBar> foo = (IBar)new Bar();

但还是允许写这个?

Foo<Bar> foo = new Bar();

我收到这个错误:

Cannot implicitly convert type IBar to Foo< IBar >. An explicit conversion exists (are you missing a cast?)

我知道我不能对接口(interface)使用隐式运算符,但为什么当接口(interface)是通用参数时我不能使用它们?

最佳答案

如果您删除通用参数并且只有 operator Foo(IBar t),它会引发 CS0552 .

You cannot create a user-defined conversion to or from an interface. If you need the conversion routine, resolve this error by making the interface a class or derive a class from the interface.

因此不允许用户定义接口(interface)之间的转换。这与您遇到的第一个错误有关:

Cannot implicitly convert type IBar to Foo< IBar >. An explicit conversion exists (are you missing a cast?)

如果已经存在显式转换(现在从 IBarFoo),则不可能存在隐式转换。

因此您不能重载来自或指向接口(interface)的用户定义转换,因为已经为该类型定义了一个内置转换(尽管是显式转换)。

关于c# - 接口(interface)、泛型和隐式操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33754309/

相关文章:

c# - Linq OrderBy 不对原始集合进行排序吗?

c# - 区分类泛型类型参数和方法泛型类型参数

c# - COM接口(interface)指南

c# - 在接口(interface)内部声明 IEnumerable<T>,同时在具体类中声明 IList<T>

c# - 不确定我在 .net 应用程序中的方法

c# - 如何从对 web 服务的请求中获取客户端 IP 地址

c# - 我怎样才能等待最短时间?

java - 对 Java 集合使用泛型的意外行为

c# - 声明有界类型的泛型字典

java - jxl API : why writablesheet is an interface?