c#Activator.CreateInstace我如何转换为通用基类型?

时间:2017-10-28 15:41:18

标签: c# generics reflection casting

我试图建立一副牌(有许多不同类型的牌组),使用基于派生类型的套装,颜色,等级的泛型。我在如何使用反射创建它们时出现问题,然后将生成的对象强制转换为基础的PlayingCard类型的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 PlayingCard<Name, Color, Rank>
        var fpc = Activator.CreateInstance(constructable);
        this.cards[0] = fpc; 
    }
 }

1 个答案:

答案 0 :(得分:-1)

using System;

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

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

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

public interface IPlayingCard<out TName, out TColor, out TRank>
//where TName : Name, new()
//where TColor : Color, new()
//where TRank : Rank, new()
{ }

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


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

    public DeckOfCards() { }

    public void BuildDeckOfCards()
    {
        this.cards = new IPlayingCard<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 PlayingCard<Name, Color, Rank>
        var fpc = Activator.CreateInstance(constructable);
        this.cards[0] = (IPlayingCard<Name, Color, Rank>)fpc;
    }
}