gpt4 book ai didi

c# 如何在函数中使用实例化的对象属性(这是一个列表)?

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:51 25 4
gpt4 key购买 nike

我有两个类(class)。具有 Name、Balance 和 Cards 属性的玩家类:

class Player
{
public string Name;
public decimal Balance;
public List<Card> Cards; // My question is related to this property
}

还有一个 Card 类:

class Card
{
public string Name;
public int Attack;
public int Defense;
public decimal Cost;
}

我为玩家实例化了一个对象:

var player = new Player("Ahmad", 100);

还有一张卡片:

var card = new Card("Mino", 3, 3, 200);

然后将卡片添加到玩家的卡片中:

player.Cards[0] = card;

我可以简单地在实例化它的主要方法上显示它,但问题是:如何在函数中访问玩家的卡片?像这样:

///<summary>
/// Function to show current cards
/// </summary>
public static void ViewCards(object player)
{
var cards = player.Cards // This line doesn't work
foreach (var card in cards)
{
Console.WriteLine($"{card.Name}");
Console.WriteLine($"Attack: {card.Attack}");
Console.WriteLine($"Defense: {card.Defense}");
Console.WriteLine($"Cost: ${card.Cost}");
}
}

最佳答案

更改方法签名更改播放器参数,从 ObjectPlayer

public static void ViewCards(Player player)
{
}

关于c# 如何在函数中使用实例化的对象属性(这是一个列表)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com