c#:在扩展方法中访问对象属性
c#: Accessing object properties in Extension Methods
我目前正在编写一个 c# Rummikub 游戏。
我有一个名为 Card 的对象,它具有 Value 和 Color 属性。
此外,在玩家的Class中,我有一个卡牌列表(玩家的手牌)。
在玩家 class 中,我写了一些只获取玩家手牌作为参数的方法。像这样的东西:
// 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?)
我应该如何编写扩展方法才能访问对象属性?
您的扩展方法是通用的,其参数类型为 Card
,它隐藏了具体的 Card
class。删除通用参数:
public static int foo(this List<Card> list)
{
return list[0].Value;
}
我目前正在编写一个 c# Rummikub 游戏。
我有一个名为 Card 的对象,它具有 Value 和 Color 属性。 此外,在玩家的Class中,我有一个卡牌列表(玩家的手牌)。
在玩家 class 中,我写了一些只获取玩家手牌作为参数的方法。像这样的东西:
// 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?)
我应该如何编写扩展方法才能访问对象属性?
您的扩展方法是通用的,其参数类型为 Card
,它隐藏了具体的 Card
class。删除通用参数:
public static int foo(this List<Card> list)
{
return list[0].Value;
}