【问题标题】:c#: Accessing object properties in Extension Methodsc#:在扩展方法中访问对象属性
【发布时间】:2015-04-26 17:54:38
【问题描述】:

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

我有一个名为 Card 的对象,它具有 ValueColor 属性。 此外,在 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;
    }

}

错误:

“卡片”不包含“价值”的定义,也没有扩展名 接受“卡片”类型的第一个参数的方法“值”可以是 找到(您是否缺少 using 指令或程序集引用?)

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

【问题讨论】:

  • 卡类没有Value的定义
  • 你能展示你的卡片类吗?它显然没有名为“Value”的公共成员。

标签: c# extension-methods


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多