我目前正在写一个c#Rummikub游戏。
我有一个名为卡的对象,它具有 Value 和 Color 属性。 此外,在播放器的课程中,我有卡片列表(玩家的手)。
在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; } }
错误:
&#39;卡&#39;不包含&#39;价值&#39;的定义没有延伸 方法&#39;价值&#39;接受第一个类型为&#39; Card&#39;可能 发现(您是否缺少using指令或程序集引用?)
我应该如何编写扩展方法以便访问对象属性?
答案 0 :(得分:4)
您的扩展方法是通用的,参数类型为Card
,它会影响具体的Card
类。删除通用参数:
public static int foo(this List<Card> list)
{
return list[0].Value;
}