Can you satisfy the general constraint with implicit conversion?

Given these types:

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 he expected him to fail, which happened. But the error message

Type "B" cannot be used as a parameter of type "T" in the general type or "Test" method. There is no implicit conversion of links from 'B' to 'A'.

But there is an implicit conversion of links from B to A. Is this just a weird message? There is no implicit link translation, as Adam Robinson's answer shows. The message is correct.

Note that MSDN says:

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

This explains why this is not allowed because Bit is not obtained fromA

+5
4

, , , . - , . , :

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

, , foo bar . A, ( ) foo. , .

, , , ( ), ( ) , . :

class A { }
class B : A { }

foo bar. . , , :

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

, , .

, , MSDN , .

+9

.

. , , , . , .

- , :

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

, , :

public void Bar<T>(T obj) where T : A
{       
    obj.Foo();
    obj.Foo();
    obj.Foo();
}

( : Bar(new B())), NEW , Foo B. , . , ? , , ? , ...

+7

, , .

, , 6.1.6 #. , :

, , . , , , .

:

:

  • .
  • S T, S T.
  • S T, S T.
  • S T, S T.
  • S SE T TE, , :
    • S T . , S T .
    • SE TE .
    • SE TE.
  • System.Array , .
  • S [] System.Collections.Generic.IList , S .
  • System.Delegate , .
  • .
  • T, T0 T0 T.
  • T, T0 T0 - (ยง13.1.3.2) T.
  • , , , , . . ยง6.1.10 .
+1

B A.

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

, . " " ( 6.1.6) " " ( 6.1.10), .

Reverse conversion means that you can convert a link to a given object from one type to another ("reference conversions ... never change the reference identifier of the converted object").

A custom implicit conversion can (like you) return a new, different object.

-1
source

All Articles