samedi 28 octobre 2017

c# Activator.CreateInstace how do i cast to generic base type?

I'm attempting to build a deck of cards (there are many different types of decks of cards) using generics based on derived types for suit, color, rank. I'm having an issue in how to create them using reflection and then cast the resulting object to the base PlayingCard type PlayingCard

    public class Name {}
    public class SpadesName : Name {}

    public class Color {}
    public class BlackColor : Color {}

    public class Rank {}
    public class AceRank : Rank {}

    public class PlayingCard<TName, TColor, TRank>
     where TName: Name, new()
     where TColor: Color, new()
     where TRank: Rank, new()
    {}

    public class DeckOfCards
    {
    public PlayingCard<Name, Color, Rank>[] cards;

    public DeckOfCards() {}

    public void BuildDeckOfCards()
    {
        this.cards = new PlayingCard<Name, Color, Rank>[52];

        Type[] fpcTypeArgs = { typeof(SpadesName), typeof(BlackColor), typeof(AceRank) };
        Type fpcType = typeof(PlayingCard<,,>);
        Type constructable = fpcType.MakeGenericType(fpcTypeArgs);

        // the problem is here.. this will not cast.
        // how do I create an object using reflection and cast it to the generic base type type PlayingCard<Name, Color, Rank>
        var fpc = Activator.CreateInstance(constructable);
        this.cards[0] = fpc; 
    }
 }





Aucun commentaire:

Enregistrer un commentaire