开发者

Implicit Operator Conversion and Generics

开发者 https://www.devze.com 2022-12-17 03:18 出处:网络
Why does this conversion not work? public interface IMyInterface { } public interface IMyInterface2 : IMyInterface

Why does this conversion not work?

public interface IMyInterface
{
}

public interface IMyInterface2 : IMyInterface
{
}

public class MyContainer<T> where T : IMyInterface
{
     public T 开发者_StackOverflow中文版MyImpl {get; private set;}
     public MyContainer()
     {
          MyImpl = Create<T>();
     }
     public static implicit T (MyContainer<T> myContainer)
     {
        return myContainer.MyImpl;
     }
}

When I use my class it causes a compile time error:

IMyInterface2 myImpl = new MyContainer<IMyInterface2>();

Cannot convert from MyContainer<IMyInterface2> to IMyInterface2...hmmmm


You cannot define an implicit conversion to an interface. Therefore your generic implicit operation is not going to be valid for interfaces. See blackwasp.co.uk

You may not create operators that convert a class to a defined interface. If conversion to an interface is required, the class must implement the interface.

You may just have to end up writing the following, without implicit magic:

IMyInterface2 myImpl = new MyContainer<IMyInterface2>().MyImpl;


It has to do with the fact that IMyInterface2 is an interface, if you replace it with

public class MyClass2 : IMyInterface
{
}

it does work.

Here is the reference, 10.9.3

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号