为什么C#中的这种隐式类型转换失败? [英] Why does this implicit type conversion in C# fail?

查看:149
本文介绍了为什么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>.最终,我希望能够如下使用此类:

As you can see, it provides an implicit type conversion operator for TWrapped<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)
{
    /* ... */
} 

问题:

但是,上述using子句中的类型转换失败.虽然可以直接将new X()分配给wrappedIX,但是不允许我将任何类型为IX的东西分配给它.编译器将抱怨以下错误:

Problem:

However, the type conversion in the above using clause fails. While I can assign a new X() directly to wrappedIX, I am not allowed to assign anything of type IX to it. The compiler will complain with the following error:

编译器错误CS0266:无法将类型'IX'隐式转换为'Wrapped< IX>'.存在明确的onversion(您是否缺少演员表?)

我不明白这一点.这是什么问题?

I don't understand this. What's the problem here?

推荐答案

我相信是因为IX是接口.编译器认为,也许IX类型的值可能已经从Wrapped<IX>派生了(即使Wrapped<T>是密封的),所以它不使用转换.

I believe it's because IX is an interface. 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.

在C#3.0规范的6.4.3和6.4.4节中,详细信息非常复杂.基本上因为IX是接口,所以没有任何类型包含",这意味着6.4.4中的后续步骤失败.

The details are quite complicated, in sections 6.4.3 and 6.4.4 of the C# 3.0 spec. Basically because IX is an interface, it's not "encompassed by" any types, which means a later step in 6.4.4 fails.

我建议您使用此方法创建非通用类型Wrapped:

I suggest you create a non-generic type Wrapped with this method:

public static Wrapped<T> Of<T>(T item)
{
    return new Wrapped<T>(item);
}

然后您可以编写:

using (Wrapped<IX> wrappedIX = Wrapped.Of(plainIX))

出于各种原因,基本转换可能会有些棘手-IMO通常更易于理解简单的方法.

Basically conversions can be a bit tricky for various reasons - simple methods are generally easier to understand, IMO.

这篇关于为什么C#中的这种隐式类型转换失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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