[英]Why does this implicit type conversion in C# fail?
Let's assume I've got the following class: 假设我有以下课程:
class Wrapped<T> : IDisposable
{
public Wrapped(T obj) { /* ... */ }
public static implicit operator Wrapped<T>(T obj)
{
return new Wrapped<T>(obj);
}
public void Dispose() { /* ... */ }
}
As you can see, it provides an implicit type conversion operator for T
→ Wrapped<T>
. 如您所见,它为
T
→ Wrapped<T>
提供了隐式类型转换运算符。 Ultimately, I would like to be able to use this class as follows: 最终,我希望能够如下使用此类:
interface IX { /* ... */ }
class X : IX { /* ... */ }
...
IX plainIX = new X();
using (Wrapped<IX> wrappedIX = plainIX)
{
/* ... */
}
However, the type conversion in the above using
clause fails. 但是,上述
using
子句中的类型转换失败。 While I can assign a new X()
directly to wrappedIX
, I am not allowed to assign anything of type IX
to it. 尽管我可以直接向
wrappedIX
分配一个new X()
,但我不能为其分配任何类型为IX
的东西。 The compiler will complain with the following error: 编译器将抱怨以下错误:
Compiler error CS0266: Cannot implicitly convert type 'IX' to 'Wrapped<IX>'.
编译器错误CS0266:无法将类型'IX'隐式转换为'Wrapped <IX>'。 An explicit onversion exists (are you missing a cast?)
存在明确的onversion(您是否缺少演员表?)
I don't understand this. 我不明白 What's the problem here?
这是什么问题
I believe it's because IX
is an interface. 我相信这是因为
IX
是一个接口。 The compiler thinks that maybe a value of type IX
could already be derived from Wrapped<IX>
(even if Wrapped<T>
is sealed) so it doesn't use the conversion. 编译器认为也许
IX
类型的值可能已经从Wrapped<IX>
派生了(即使Wrapped<T>
被密封了),所以它不使用转换。
The details are quite complicated, in sections 6.4.3 and 6.4.4 of the C# 3.0 spec. 详细信息非常复杂,请参见C#3.0规范的6.4.3和6.4.4节。 Basically because
IX
is an interface, it's not "encompassed by" any types, which means a later step in 6.4.4 fails. 基本上因为
IX
是一个接口,所以它不会被任何类型“包围”,这意味着6.4.4中的后续步骤将失败。
I suggest you create a non-generic type Wrapped
with this method: 我建议您创建一个使用此方法
Wrapped
的非泛型类型:
public static Wrapped<T> Of<T>(T item)
{
return new Wrapped<T>(item);
}
Then you can just write: 然后,您可以编写:
using (Wrapped<IX> wrappedIX = Wrapped.Of(plainIX))
Basically conversions can be a bit tricky for various reasons - simple methods are generally easier to understand, IMO. 出于各种原因,转换基本上会有些棘手-IMO通常会更容易理解简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.