Skip to main content
 首页 » 编程设计

c#:在扩展方法中访问对象属性

2024年02月06日14dflying

我目前正在编写一个 c# Rummikub 游戏。

我有一个名为 Card 的对象,它具有 Value 和 Color 属性。 此外,在 Player 的类中,我有一个卡片列表(玩家的手)。

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

我应该如何编写扩展方法才能访问对象属性?

请您参考如下方法:

您的扩展方法是通用的,其参数类型为 Card,它隐藏了具体的 Card 类。删除泛型参数:

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