简体   繁体   中英

c#: Accessing object properties in Extension Methods

I'm currently writing ac# Rummikub game.

I have an object named Card that has Value and Color properties. Also, inside Player 's Class, I have a list of cards (player's hand).

In the Player class, I wrote some methods that get only the player's hand as parameter. stuff like:

  // Determines what card should the CPU throw. public int CardToThrow(List<Card> CPUHand). // Call: int cardToThrow = Player1.CardToThrow(Player1.Hand); 

I want to be able to call the function like this:

  int cardToThrow = Player1.Hand.CardToThrow(); 

When I tried to write the Extension Method, I didn't manage to acces the card's properties:

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

Error:

'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?)

How should I write the extension methods so I could access the object properties?

Your extension method is generic with a parameter type of Card which is shadowing the concrete Card class. Remove the generic parameter:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM