C# Is Not Assignable Type - Generics

后端 未结 2 983
粉色の甜心
粉色の甜心 2021-01-18 13:42

So I\'m just hacking around with a state machine type I was working on and mostly wanting to just try out the Activator.CreateInstance method to see what it was like, and I

2条回答
  •  耶瑟儿~
    2021-01-18 14:06

    That fails because generics are not covariant. The problem can be seen here:

    TransitionContainer value = new TransitionContainer();
    

    That gives you the same error. You also get this error with something as simple as:

    List list = new List();
    

    Visual Studio tells you (basically) that:

    Cannot implicitly convert type 'List' to 'List'
    

    What you need to do is convert the object. You could create a Convert method that returns a TransitionContainer and then use .Add(typeof(TTransition), transitionContainer.Convert()) (or whatever you name it).

    But the most painless option is to create an implicit conversion for your TransitionContainer object by adding this static method:

    public static implicit operator TransitionContainer(TransitionContainer value)
    {
        return new TransitionContainer() { StateTo = value.StateTo, Transition = value.Transition };
    }
    

    And that's it. :)

    Of course, you will have to copy everything needed for it to work, in this case it seems these two objects are enough.

提交回复
热议问题