你能满足使用的隐式转换一个通用的约束? [英] Can you satisfy a generic constraint with an implicit conversion?

查看:103
本文介绍了你能满足使用的隐式转换一个通用的约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这些类型的:

class A { }
class B
{
    public static implicit operator A(B me)
    {
        return new A();
    }
}

class Test<T> where T : A { }



我试过

I tried

var b = new Test<B>();

和希望它失败,这的确如此。但是,错误消息

And expected it to fail, which it did. But the error message is

在'B'型不能在泛型类型或方法可以用作类型参数'T'测试 。有一个从'B'到'A'的隐式引用转换。

The type 'B' cannot be used as type parameter 'T' in the generic type or method 'Test'. There is no implicit reference conversion from 'B' to 'A'.

<击>但是,是从B到A的隐式引用转换是这只是一个奇怪的消息?还有的的隐式引用转换亚当罗宾逊的答案所示。该消息是正确的。

But there is an implicit reference conversion from B to A. Is this just a strange message? There is not an implicit reference conversion as Adam Robinson's answer shows. The message is correct.

注意的 MSDN说:

其中T:(基类名称) - 类型参数必须是或从派生指定的基类。

where T : (base class name) - The type argument must be or derive from the specified base class.

这可以解释为什么它没有因为 b允许做不是从 A

Which explains why it is not allowed since B does not derive from A

推荐答案

没有,什么你想做是不可能的。一个隐含的参考的转换是不一样的事,作为一个隐含的键入的转换。您的代码定义了一个隐式类型转换,这是在那里你可以做到以下几点:

No, what you're trying to do is not possible. An implicit reference conversion is not the same thing as an implicit type conversion. Your code defines an implicit type conversion, which is where you could do the following:

B foo = new B();
A bar = foo;

请注意,但是,现在包含不同的引用。隐式类型转换创建的新的 A 的实例,这应该是(按照约定)逻辑上等同于。但问题是,这是一个不同的参考。

Note, however, that foo and bar now contain different references. The implicit type conversion creates a new instance of A that should be (by convention) logically equivalent to foo. But the point is that it's a different reference.

一个的参考的转换将是其中引用本身不会改变,这意味着该类型问题必须从(上课)无论是继承或实现(用于接口)的问题的类型。如果我这样做:

A reference conversion would be where the reference itself does not change, which means that the type in question must either inherit from (for classes) or implement (for interfaces) the type in question. If I do this:

class A { }
class B : A { }

然后我上面的代码将现在持有相同的参考和。这是由隐式引用转换的意思。相反,一个的明确的引用转换将被向下转型,是这样的:

Then my code above will now hold the same reference in foo and bar. This is what is meant by an implicit reference conversion. Conversely, an explicit reference conversion would be downcasting, like this:

A foo = new B();
B bar = (B)foo;

再次引用是相同的,但演员是明确的。

Again, the references are the same, but the cast was explicit.

因此,简而言之,MSDN文档更清晰,但不太精确。

So, in short, the MSDN documentation is clearer but less precise.

这篇关于你能满足使用的隐式转换一个通用的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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