我試圖用西裝,顏色,等級派生類型的泛型來構建一副牌(有許多不同類型的牌)。我在如何使用反射來創建它們,然後一個問題投產生的對象基本遊戲牌類遊戲牌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