我试图用西装,颜色,等级派生类型的泛型来构建一副牌(有许多不同类型的牌)。我在如何使用反射来创建它们,然后一个问题投产生的对象基本游戏牌类游戏牌c#Activator.CreateInstace如何转换为泛型基类型?
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;
}
}
这是关于最糟糕的仿制药滥用我在几年看到。为什么你会以这种方式使用泛型?只需使用'Suit'和'Rank'属性创建一个Card类。 – InBetween
@InBetween是的,我知道这些类型的评论将张贴,记录时间不会少于..作为帖子说,我试图解决这个使用泛型。这里有一张你看不到的大图。我很清楚,这可以具体完成。请尊重帖子的原因。 – Kirk
没有任何运行时反射会改变'PlayingCard <名称,颜色,等级>和'PlayingCard'的不同类型。如果创建后者的实例,则不能将其存储在前者的数组中。你真正追求的东西可能或不可能,但如果你不想要显示那是什么,也不希望别人在答案中解决这个问题,我看不出有什么办法给出有用的答案对这个问题。 –
hvd