【发布时间】:2017-10-28 15:41:18
【问题描述】:
我正在尝试使用基于套装、颜色、等级的派生类型的泛型来构建一副纸牌(有许多不同类型的纸牌)。我在如何使用反射创建它们然后将生成的对象转换为基本 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;
}
}
【问题讨论】:
-
这是我多年来见过的最严重的仿制药滥用。为什么你会以这种方式使用泛型?只需使用
Suit和Rank属性创建一个Card类。 -
@InBetween 是的,我知道这些类型的 cmets 会在创纪录的时间内发布。正如帖子所述,我正在尝试使用泛型解决这个问题。这里有一张你看不到的更大的图片。我很清楚这可以具体做到。请尊重发帖的原因。
-
没有多少运行时反射会改变
PlayingCard<Name, Color, Rank>和PlayingCard<SpadesName, BlackColor, AceRank>是不同类型的事实。如果创建后者的实例,则不能将其存储在前者的数组中。您真正追求的可能是也可能不是,但是如果您不想展示那是什么并且不想让其他人在答案中解决这个问题,我看不出有任何方法可以提供有用的答案这个问题。 -
这里有一张你看不到的大图。那么,首先要这样说,如果你期待误解的话,更是如此。查看 c# 泛型类型差异,在这个主题上一定有无数关于 SO 的问题,所以你会发现阅读这个主题相当容易。长话短说,
Bowl<Animal>和Bowl<Turtle>是两种截然不同的类型,只有在非常特定的情况下才能使用一种代替另一种。 -
@InBetween 再次感谢您的另一条未回答的评论。
标签: c# generics reflection casting