C#编译器错误?为什么没有这种隐含的用户定义的转换编译? [英] C# compiler bug? Why doesn't this implicit user-defined conversion compile?

查看:116
本文介绍了C#编译器错误?为什么没有这种隐含的用户定义的转换编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下结构:

 公共结构美孚< T>
{
   公共美孚(T OBJ){}   公共静态隐运营商美孚< T>(T输入)
   {
      返回新的Foo< T>(输入);
   }
}

这code编译:

 私人美孚< ICloneable> MakeFoo()
{
    串c =你好;
    返回℃; //成功:字符串是ICloneable,ICloneable隐式​​转换为富< ICloneable>
}

但是,这code不能编译 - 为什么

 私人美孚< ICloneable> MakeFoo()
{
    ICloneable C =你好;
    返回℃; //错误:ICloneable不能转换为富< ICloneable取代。 WTH?
}


解决方案

显然,当类型之一是接口的隐式用户定义的转换不起作用。从C#规格:


6.4.1允许用户定义的转换

要声明

C#只允许某些用户定义的转换。尤其是,它是不可能重新定义一个已经存在的隐式或显式转换。
对于给定的源类型S和目标类型T,如果S或T是可空类型,让S0和T0引用它们的基础类型,否则S0和T0分别等于S和T。类或结构允许声明从源类型S转换到目标类型T仅在以下所有条件都为真:


  • S0和T0是不同的类型。

  • 无论是S0或T0为类或结构类型,其中运算符声明发生。

  • 无论S0也不T0为一个接口类型

  • 不包括用户定义的转换,转换不存在从S到T或从T到秒。


在你的第一个方法,这两种类型都没有的接口类型,因此用户定义的隐式转换工作。

的规格也不是很清楚,但在我看来,如果所涉及的类型之一是接口类型,编译器甚至不尝试查找任何用户定义的隐式转换。

Given the following struct:

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

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

This code compiles:

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

But this code doesn't compile -- why?

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

解决方案

Apparently, implicit user defined conversions don't work when one of the types is an interface. From the C# specs:


6.4.1 Permitted user-defined conversions

C# permits only certain user-defined conversions to be declared. In particular, it is not possible to redefine an already existing implicit or explicit conversion. For a given source type S and target type T, if S or T are nullable types, let S0 and T0 refer to their underlying types, otherwise S0 and T0 are equal to S and T respectively. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true:

  • S0 and T0 are different types.
  • Either S0 or T0 is the class or struct type in which the operator declaration takes place.
  • Neither S0 nor T0 is an interface-type.
  • Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.


In your first method, both types are not interface types, so the user defined implicit conversion works.

The specs are not very clear, but it seems to me that if one of the types involved is an interface type, the compiler doesn't even try to look up any user-defined implicit conversions.

这篇关于C#编译器错误?为什么没有这种隐含的用户定义的转换编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆