背景:
让我们假设我有下面的类:为什么C#中的隐式类型转换失败?
class Wrapped<T> : IDisposable
{
public Wrapped(T obj) { /* ... */ }
public static implicit operator Wrapped<T>(T obj)
{
return new Wrapped<T>(obj);
}
public void Dispose() { /* ... */ }
}
正如你所看到的,它提供了T
→ Wrapped<T>
的隐式类型转换操作符。最终,我想能够使用这个类,如下所示:
interface IX { /* ... */ }
class X : IX { /* ... */ }
...
IX plainIX = new X();
using (Wrapped<IX> wrappedIX = plainIX)
{
/* ... */
}
问题:
然而,上述using
子句中的类型转换失败。虽然我可以将new X()
直接指定给wrappedIX
,但我不能将IX
类型的任何内容指定给它。编译器会报错以下错误:
Compiler error CS0266: Cannot implicitly convert type 'IX' to 'Wrapped<IX>'. An explicit onversion exists (are you missing a cast?)
我不明白这一点。这里有什么问题?
compilable if if replace“IX plainIX = new X();”用“X plainIX = new X();” – Nagg 2010-03-26 19:29:01
@Nagg:因为我想实现的目标(即在现有的* COM库*上设计一个流畅的接口),所以对接口进行编程是绝对必要的。因此,不幸的是,你的建议不是一个可行的选择。 – stakx 2010-03-26 19:42:30