【问题标题】:Change a line of code in a while loop在while循环中更改一行代码
【发布时间】:2016-08-15 00:12:14
【问题描述】:

这里是 C# 初学者。我想知道在 c# 中是否可以实现以下操作。

我有以下有效的代码(但目前还没有做太多):

while (i != 10)
        {
            i++;
            _playerCard1.Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
        }

现在我的程序中有其他图像字段,名为 _playerCard2、_playerCard3 等等。我想知道的是是否可以让 while 循环使用 i 变量遍历不同的 Image 字段。像这样的:

while (i != 10)
        {
            i++;
            _playerCard{i}.Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
        }

我知道上面的代码行不通,只是想知道它是否可行,如果可以,我将如何编写代码?谢谢你的帮助!

【问题讨论】:

    标签: c#


    【解决方案1】:

    您需要的是playerCard 的数组或列表,然后您可以迭代每个项目。例如。

    //create a simple array of cards
    var playerCards = new[] { _playerCard1, _playerCard2, _playerCard3 }; 
    
    //iterate each card
    for(var i = 0; i < playerCards.length; i++)
    {
        _playerCards[i].Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-20
      • 2021-10-18
      • 1970-01-01
      • 2013-10-24
      • 2020-07-27
      • 1970-01-01
      • 2014-01-30
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多