[英]c#: Accessing object properties in Extension Methods
I'm currently writing ac# Rummikub game. 我目前正在编写ac#Rummikub游戏。
I have an object named Card that has Value and Color properties. 我有一个名为Card的对象,该对象具有Value和Color属性。 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. 在Player类中,我编写了一些方法,这些方法仅将玩家的手作为参数。 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?) 'Card'不包含'Value'的定义,找不到扩展方法'Value'接受类型为'Card'的第一个参数(您是否缺少using指令或程序集引用?)
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. 您的扩展方法是通用的,参数类型为Card
,它遮盖了具体的Card
类。 Remove the generic parameter: 删除通用参数:
public static int foo(this List<Card> list)
{
return list[0].Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.