Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何避免300箱的开关块?_C#_Switch Statement_Maintainability - Fatal编程技术网

C# 如何避免300箱的开关块?

C# 如何避免300箱的开关块?,c#,switch-statement,maintainability,C#,Switch Statement,Maintainability,我正在尝试将300个挑战添加到我的程序中,但仅当CompletionValue.IsChecked=false时才显示它们 如果你正在创建这个程序。您将如何存储这些挑战? 我用的是开关,但是有300个箱子是多余的,有更好的方法吗 任何关于改进代码的建议都将受到赞赏。 我对此有些陌生 Random rand = new Random(); // Constructor public MainPage() { InitializeComponent()

我正在尝试将300个挑战添加到我的程序中,但仅当CompletionValue.IsChecked=false时才显示它们

如果你正在创建这个程序。您将如何存储这些挑战? 我用的是开关,但是有300个箱子是多余的,有更好的方法吗

任何关于改进代码的建议都将受到赞赏。 我对此有些陌生

    Random rand = new Random();
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        AnswerValue.Visibility = Visibility.Collapsed;
        Load();

    }


    private void Load()
    {
        int random = rand.Next(1, 4);
        switch (random)
        {
            case 1:
                Challenge1();
                break;
            case 2:
                Challenge2();
                break;
            case 3:
                Challenge3();
                break;
        }
    }

    private void Challenge1()
    {
        DifficultyValue.Text = "20%";
        CompletionValue.IsChecked = false;
        TitleValue.Text = "Chicken or Egg?";
        QuestionValue.Text = "Can you answer the ancient question: Which came first the chicken of the egg?";
        bmp.UriSource = new Uri("Images/Challenge1.png", UriKind.Relative);
        ImageValue.Source = bmp;
        ImageValue.Visibility = Visibility.Visible;
        ResourceValue.Text = "Resource: Brain Games";
        AnswerValue.Text = "The Egg. According to paleontologists, reptiles and dinosaurs existed long before birds and chickens.  Fossilized eggs dating back on hundred millions years have been uncovered. Thus it can be said that eggs came before chickens.";

    }

    private void Challenge2()
    {
        DifficultyValue.Text = "25%";
        CompletionValue.IsChecked = false;
        TitleValue.Text = "Halving Seven";
        QuestionValue.Text = "Can you prove that seven is half of twelve?";
        bmp.UriSource = new Uri("Images/Challenge2.png", UriKind.Relative);
        ImageValue.Source = bmp;
        ImageValue.Visibility = Visibility.Visible;
        ResourceValue.Text = "Resource: Yahoo Questions";
        AnswerValue.Text = "Roman numeral for 12 - XII \n Cut the roman numeral in half. you will get VII, which is 7.";

    }

    private void Challenge3()
    {
        DifficultyValue.Text = "25%";
        CompletionValue.IsChecked = false;
        TitleValue.Text = "Three-coin flip";
        QuestionValue.Text = "You ask a friend about probability, and he tells you the following: The odds of three tossed coins turning up all heads or all tails is one in two, that is, fifty-fifty. That’s because anytime you toss three coins, at least two must match, either two heads or two tails.  So that means the third coin—which is equally likely to be heads or tails—determines the odds.” Is your friend right? If not, what are the odds of three tossed coins turning up all heads or all tails?";
        bmp.UriSource = new Uri("Images/Challenge3.png", UriKind.Relative);
        ImageValue.Source = bmp;
        ImageValue.Visibility = Visibility.Visible;
        ResourceValue.Text = "Resource: Brain Games";
        AnswerValue.Text = "Answer will be available soon";
    }

您可以将挑战保存在数据库或文件中。我确实看到您使用的是随机数,并且只显示一个挑战。数据库可以是

ChallengeId, DifficultyValue, TitleValue ... 

ChallengeId将是问题ID号。因此,根据生成的随机数,您可以选择特定的ChallengeId和相关数据

您真正应该研究的是封装和多态代码。通过将类似属性封装到一个类中,您可以更好地将“挑战”作为一个整体来表示,并且能够重复使用必须反复键入的部分(
.Text=“…”
)将使您未来的编码生活无限美好。诚然,即使像我下面提到的那样,对
Challenge
实体列表进行编码也不是件有趣的事,你必须在某处输入数据。我们将考虑这是一个编码练习,您可以很容易地修改下面的代码来从数据库或序列化文件中填充<代码>挑战> /代码>。p>
public class Challenge
{
    public int Id {get;set;}
    public int Difficulty {get;set;}
    public bool IsCompleted {get;set;}
    public string Title {get;set;}
    public string Question {get;set;}
    public string Answer {get;set;}
}

public class MainPage
{
    private List<Challenge> _challenges;
    private Random rand = new Random();
    public MainPage()
    {
        _challenges = new List<Challenge> {
            new Challenge {
                    Id = 1,
                    Difficulty = 20,
                    Title = "What came first?",
                    Question =  "The chicken or the egg?",
                    Answer = "The egg." },
            new Challenge {
                    Id = 2,
                    Difficulty = 30,
                    Title = "Make 7 from 12?",
                    Question =  "Can you prove 7 is half of 12?",
                    Answer = "VII" }};
    }

    public void LoadChallenge(Challenge challenge)
    {
        Difficulty.Test = String.Format("%{0}", callenge.Difficulty);
        Completeted.Value = challenge.IsCompleted;
        Title.Test = challenge.Title;
        // etc
    }

    public void StartNewChallenge()
    {
        Challenge nextChallenge = null;
        while(nextChallenge == null)
        {
            var nextId = rand.Next(1,2);
            nextChallenge = _challenges
                .Where(x => x.Id == nextId && !x.IsCompleted)
                .SingleOrDefault(); // default to null if completed == true
        }
        LoadChallenge(nextChallenge);
    }

}
公开课挑战赛
{
公共int Id{get;set;}
公共整数{get;set;}
公共布尔已完成{get;set;}
公共字符串标题{get;set;}
公共字符串问题{get;set;}
公共字符串答案{get;set;}
}
公共类主页
{
私人名单(挑战),;
private Random rand=new Random();
公共主页()
{
_挑战=新列表{
新挑战{
Id=1,
难度=20,
Title=“先来的是什么?”,
问题=“鸡还是蛋?”,
答案=“鸡蛋。”},
新挑战{
Id=2,
难度=30,
Title=“从12变为7?”,
问=“你能证明7是12的一半吗?”,
Answer=“VII”};
}
公开挑战(挑战)
{
Test=String.Format(“%{0}”,callenge.demobility);
completeded.Value=challenge.IsCompleted;
Title.Test=challenge.Title;
//等
}
公共无效开始新挑战()
{
挑战nextChallenge=null;
while(nextChallenge==null)
{
var nextId=rand.Next(1,2);
下一个挑战=\u挑战
.Where(x=>x.Id==nextId&&!x.IsCompleted)
.SingleOrDefault();//如果完成,则默认为null==true
}
LoadChallenge(下一个挑战);
}
}

你们的挑战看起来非常相似,对吧?在这种情况下,您需要提取一个公共数据结构,并将每个挑战表示为一段数据

通过对挑战的统一表示,可以根据特定挑战ID的挑战数据设置UI

始终可以将数据移动到XML文件、JSON文件或数据库中,但首先要看看简单的C#解决方案是否适合您:

// Note: This example is simplified for readability

// Here is the common data structure that can represent all challenges
private class Challenge
{
    public string Title { get; set; }
    public string Question { get; set; }
    public string ImagePath { get; set; }
}

// All of the challenges are defined right here, as simple data
private Challenge[] _allChallenges = new Challenge[]
{
    new Challenge
    {
        Title = "Chicken or Egg?",
        Question = "Can you answer the ancient question: Which came first the chicken of the egg?",
        ImagePath = "Images/Challenge1.png",
    },
    new Challenge
    {
        Title = "Halving Seven?",
        Question = "Can you prove that seven is half of twelve?",
        ImagePath = "Images/Challenge1.png",
    },
}

// Choosing challenges is as simple as indexing into the array
private void Load()
{
    int random = rand.Next(1, 4);
    Challenge chosenChallenge = _allChallenges[random];
    LoadChallenge(chosenChallenge);
}

// Setting up the UI for a challenge means extracting information from the data structure
private void LoadChallenge(Challenge chosenChallenge)
{
    TitleValue.Text = chosenChallenge.Title;
    QuestionValue.Text = chosenChallenge.Text;
    bmp.UriSource = new Uri(chosenChallenge.ImagePath, UriKind.Relative);
    ImageValue.Source = bmp;
    ImageValue.Visibility = Visibility.Visible;
}
你可以认为这是一种形式。程序的一个重要部分,挑战本身,已经从命令语句(设置UI属性)转换为非常简单的数据声明


通过进行此转换,您甚至可以检查每个挑战,以确保所有部分都已填写。然后,您将确保为300项挑战中的每一项设置了标题、问题、资源、答案等。

另一种选择可能是某种工厂方法:

MyForm.cs

public class MyForm
{
    Random rand = new Random();
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        AnswerValue.Visibility = Visibility.Collapsed;
        Load();
    }

    private void Load()
    {
        int random = rand.Next(1, 4);
        DisplayChallenge(ChallengeFactory.GetChallenge(random));
    }

    private void DisplayChallenge(ChallengeFactory.Challenge challengeToDisplay)
    {
        DifficultyValue.Text = String.Format("{0}%", challengeToDisplay.Difficulty);
        CompletionValue.IsChecked = challengeToDisplay.IsChecked;
        TitleValue.Text = challengeToDisplay.Title;
        QuestionValue.Text = challengeToDisplay.Question;
        ImageValue.Source = challengeToDisplay.ImageSource;
        ImageValue.Visibility = challengeToDisplay.Visible;
        ResourceValue.Text = challengeToDisplay.ResourceValue;
        AnswerValue.Text = challengeToDisplay.Answer;
    }
}
public static class ChallengeFactory
{
    public class Challenge
    {
        public int Difficulty { get; set; }
        public bool IsChecked { get; set; }
        public string Title { get; set; }
        public string Question { get; set; }
        public Uri ImageSource { get; set; }
        public bool Visible { get; set; }
        public string ResourceValue { get; set; }
        public string Answer { get; set; }

        private Challenge(int difficulty, bool isChecked, string title, string question, Uri imageSource, bool visible, string resourceValue, string answer)
        {
            // assign each of the arguments to the instance properties
        }
    }

    public static Challenge GetChallenge(int challengeNumber)
    {
        switch(challengeNumber)
        {
            case 1:
                return new Challenge(20, false, "Chicken or Egg?", "Can you answer the ancient question: Which came first the chicken of the egg?", new Uri("Images/Challenge1.png", UriKind.Relative), true, "Resource: Brain Games", "The Egg...");
            break;
            case 2:
                // new challenge for challenge #2
            break;
            case 3:
                // new challenge for challenge #3
            break;
        }
    }
}
ChallengeFactory.cs

public class MyForm
{
    Random rand = new Random();
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        AnswerValue.Visibility = Visibility.Collapsed;
        Load();
    }

    private void Load()
    {
        int random = rand.Next(1, 4);
        DisplayChallenge(ChallengeFactory.GetChallenge(random));
    }

    private void DisplayChallenge(ChallengeFactory.Challenge challengeToDisplay)
    {
        DifficultyValue.Text = String.Format("{0}%", challengeToDisplay.Difficulty);
        CompletionValue.IsChecked = challengeToDisplay.IsChecked;
        TitleValue.Text = challengeToDisplay.Title;
        QuestionValue.Text = challengeToDisplay.Question;
        ImageValue.Source = challengeToDisplay.ImageSource;
        ImageValue.Visibility = challengeToDisplay.Visible;
        ResourceValue.Text = challengeToDisplay.ResourceValue;
        AnswerValue.Text = challengeToDisplay.Answer;
    }
}
public static class ChallengeFactory
{
    public class Challenge
    {
        public int Difficulty { get; set; }
        public bool IsChecked { get; set; }
        public string Title { get; set; }
        public string Question { get; set; }
        public Uri ImageSource { get; set; }
        public bool Visible { get; set; }
        public string ResourceValue { get; set; }
        public string Answer { get; set; }

        private Challenge(int difficulty, bool isChecked, string title, string question, Uri imageSource, bool visible, string resourceValue, string answer)
        {
            // assign each of the arguments to the instance properties
        }
    }

    public static Challenge GetChallenge(int challengeNumber)
    {
        switch(challengeNumber)
        {
            case 1:
                return new Challenge(20, false, "Chicken or Egg?", "Can you answer the ancient question: Which came first the chicken of the egg?", new Uri("Images/Challenge1.png", UriKind.Relative), true, "Resource: Brain Games", "The Egg...");
            break;
            case 2:
                // new challenge for challenge #2
            break;
            case 3:
                // new challenge for challenge #3
            break;
        }
    }
}
请注意,我已将质询类设置为Factory类内部的嵌套类。这样做的好处是,可以将质询
的构造函数设置为私有的
(这意味着您不能创建“无效的”通过工厂方法以外的任何方法进行的质询类型。这样做的缺点是,您必须通过在质询类前面加上它的包含类(即,
ChallengeFactory
)来进一步限定质询类。我认为在这种情况下,额外的限定符是值得的


最终,我认为如果你计划在代码中定义所有挑战,你就必须在某个地方创建一个切换。正如其他人所说,通过在外部数据源(如数据库)中定义挑战,你可以显著减少需要编写的代码量(从而减少切换)使用单一方法读取、解析和创建
挑战
实例。

+1必须同意这一点。编写300个挑战似乎是个糟糕的主意。