相关疑难解决方法(0)

C#编译器错误?为什么这个隐式的用户定义转换没有编译?

给定以下结构:

public struct Foo<T>
{
   public Foo(T obj) { }

   public static implicit operator Foo<T>(T input)
   {
      return new Foo<T>(input);
   }
}
Run Code Online (Sandbox Code Playgroud)

此代码编译:

private Foo<ICloneable> MakeFoo()
{
    string c = "hello";
    return c; // Success: string is ICloneable, ICloneable implicitly converted to Foo<ICloneable>
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码没有编译 - 为什么?

private Foo<ICloneable> MakeFoo()
{
    ICloneable c = "hello";
    return c; // Error: ICloneable can't be converted to Foo<ICloneable>. WTH?
}
Run Code Online (Sandbox Code Playgroud)

c# compiler-construction

32
推荐指数
2
解决办法
2634
查看次数

标签 统计

c# ×1

compiler-construction ×1