C#我有50张其他if卡的声明,有没有办法缩短它或一次性完成所有操作?

我有一个加载并生成7个不同随机数的表单,从1到13,1是Ace,13是King.在生成7个不同的随机数后,它将每个随机数放入7个图像框中.我正在使用if语句显示图片框.

它还循环通过一系列“黑桃,心,俱乐部和钻石”,13次.

我的if语句如下:

if (cardNum == 1 && cardType ==  "Spades")
{
    pictureBox1.Image = ace_of_spades;
}
else if (cardNum == 1 && cardType == "Hearts")
{
    pictureBox1.Image = ace_of_hearts;
}
else if (...)
{
    //change picture box
} //repeat it like 50 times

是否有一种简单,容易的方法来挑选7张随机卡并在图片框中显示它们?

这是非常耗时的,就像我这样做.

解决方法

如此多的非OOP建议如何处理这个问题.这是我的解决方案,它允许每个对象跟踪自己,并将提供一种简单的方式来洗牌并获得与每张卡相关的图像(我已经写了几张纸牌游戏).

要存储实际图像,请将它们作为资源文件嵌入到项目中,并以特定方式命名:

> card_Club_1
> card_Club_2
> card_Club_3
>等……

然后,当您需要卡片图像时,您只需组合套装和值并从资源管理器请求该资源名称,如下所示.此方法需要更多的设置和规划,但会为您提供更清晰的代码.您甚至可以在一个单独的项目中执行所有这些操作,然后通过在应用程序中引用要提供一副卡片的DLL来重新使用类/资源.

enum Suit : uint
{
    Club = 0,Heart,Spade,Diamond
}
class Card
{
    public int
        Value;
    public Suit
        Suit;

    public System.Drawing.Image GetImage()
    {
        return System.Drawing.Image.FromStream(
            global::cardLibraryProject.Properties.Resources.ResourceManager.GetStream(string.Format("card_{0}_{1}",this.Suit,this.Value))
        );
    }
}
class Deck
{
    System.Collections.ArrayList
        _arr;

    private Deck()
    {
        this._arr = new System.Collections.ArrayList(52);
    }

    void Add(Card crd)
    {
        if (!this._arr.Contains(crd))
            this._arr.Add(crd);
    }

    public void Shuffle()
    {
        Random rnd = new Random(DateTime.Now.Millisecond);
        System.Collections.ArrayList tmp1 = new System.Collections.ArrayList(this._arr);
        System.Collections.ArrayList tmp2 = new System.Collections.ArrayList(52);
        while (tmp1.Count > 0)
        {
            int idx = rnd.Next(tmp1.Count);
            tmp2.Add(tmp1[idx]);
            tmp1.RemoveAt(idx);
        }
        this._arr = tmp2;
        tmp1.Clear();
        tmp2.Clear();
    }

    public static Deck CreateDeck()
    {
        Deck newDeck = new Deck();
        for (int s = 0; s < 4; s++)
            for (int i = 0; i < 13; i++)
                newDeck.Add(new Card { Value = i,Suit = (Suit)s });
        return newDeck;
    }
}
class Program
{
    public void Main(string[] args)
    {
        Deck cards = Deck.CreateDeck();
        cards.Shuffle();

        pictureBox1.Image = cards[0].GetImage();
        // code to play game would go here.  Obviously,if you took
        // my suggestion about creating a "Cards" library,then you
        // wouldn't have a "void Main" at all,and this would
        // all go in the application that was the actual game.
    }
}

相关文章

1:最直白的循环遍历方法,可以分为遍历key--value键值对以及...
private void ClearTextBox(){ foreach (var control in pnl...
原文叫看《墨攻》理解IOC概念 2006年多部贺岁大片以让人应接...
右击文件夹-&gt;安全选项卡-&gt;添加-&gt;高级-...