2015-04-26 80 views
1

我目前正在編寫一個c#Rummikub遊戲。c#:在擴展方法中訪問對象屬性

我有一個對象命名價值顏色性能。 另外,裏面的玩家的等級,我有一個卡片列表(玩家的手)。

在Player類中,我寫了一些只獲取玩家手牌的方法作爲參數。這樣的東西:

// Determines what card should the CPU throw. 
    public int CardToThrow(List<Card> CPUHand). 

    // Call: 
    int cardToThrow = Player1.CardToThrow(Player1.Hand); 

我希望能夠調用這樣的功能:

int cardToThrow = Player1.Hand.CardToThrow(); 

當我試圖寫的擴展方法,我沒能存取權限卡的屬性:

public static class HandExtensionMethods 
{ 
    public static int foo<Card>(this List<Card> list) 
    { 
     return list[0].Value; 
    } 

} 

錯誤:

'Card' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'Card' could be found (are you missing a using directive or an assembly reference?)

我應該如何編寫擴展方法以便可以訪問對象屬性?

+1

卡類沒有定義值 –

+0

您可以顯示您的卡類嗎?它顯然沒有一個名爲「價值」的公衆成員。 – Padraic

回答

4

您的擴展方法是通用的,參數類型爲Card,它是具體的Card類的陰影。刪除通用參數:

public static int foo(this List<Card> list) 
{ 
    return list[0].Value; 
} 
+0

謝謝,它工作:) –