C#编译器错误?为什么不隐式的用户定义转换编译? [英] C# compiler bug? Why doesn't this implicit user-defined conversion compile?
问题描述
给定以下结构:
public struct Foo<T>
{
public Foo(T obj) { }
public static implicit operator Foo<T>(T input)
{
return new Foo<T>(input);
}
}
此代码编译:
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?
}
推荐答案
显然,当其中一种类型是接口时不工作。从C#规范:
Apparently, implicit user defined conversions don't work when one of the types is an interface. From the C# specs:
6.4.1允许的用户定义转换
6.4.1 Permitted user-defined conversions
C#仅允许声明某些用户定义的转换。特别地,不可能重新定义已经存在的隐式或显式转换。
对于给定的源类型S和目标类型T,如果S或T是可空类型,则让S0和T0指向它们的底层类型,否则S0和T0分别等于S和T.只有在以下所有条件都成立的情况下,类或结构才允许声明从源类型S到目标类型T的转换:
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和T0是不同类型。
- S0或T0是运算符声明发生的类或结构类型。
- 排除用户定义的转化,转化不存在从S到T或从T到S。
- 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.
规范不是很清楚,但在我看来,如果涉及的类型之一是接口类型,编译器甚至不会尝试查找任何用户定义的隐式转换。
这篇关于C#编译器错误?为什么不隐式的用户定义转换编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!