有没有办法在c#中缩短这段代码?

本文关键字:段代码 代码 有没有 | 更新日期: 2023-09-27 18:11:48

我有一个作业,它告诉我创建一个文件,你插入随机字母数字字符和关键字"病毒"到文件中。我想我用的逻辑对于这个作业来说已经足够了。

我只是想知道有没有办法让我缩短我写的代码?因为我想学习更多关于如何高效编写代码的知识。我还是个新手,自学成才;欢迎建设性的反馈。这是我的任务。谢谢!: D

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RBC_Task_3 {
    class Program {
        static void Main(string[] args) {
            beginning: Console.WriteLine(
                "This program inputs a random alphanumeric array into a file.'n" +
                "The keyword '"VIRUS'" is sometimes inserted randomly inside the file.'n"
            );
            Console.WriteLine("Press any key to continue...");
            string folderName = @"c:'Top Folder";
            string path1 = Path.Combine(folderName, "File Folder");
            Directory.CreateDirectory(path1);
            if (Directory.Exists(path1)) {
                for (int i = 1; i <= 5; i++) {
                    string fileName = "file" + i + ".dat";
                    string filePath = Path.Combine(path1, fileName);
                    File.Create(filePath).Dispose();
                }
            }
            Console.ReadKey();
            Console.Clear();
            Console.Write("Press Y/y if you want to begin  ");
            string c = Console.ReadLine();
            Console.Clear();
            var rC = new Random();
            int sP = 0;
            if (c == "Y" || c == "y") {
                sP = rC.Next(1, 4);
                if (sP == 1) {
                    goto sequenceOne;
                } else if (sP == 2) {
                    goto sequenceTwo;
                } else {
                    goto sequenceThree;
                }
            } else {
                Console.WriteLine(
                    "Press Y/y if you want to begin.'nPress any key to continue"
                );
                Console.ReadKey();
                Console.Clear();
                goto beginning;
            }
            sequenceOne: var stringChars = new char[26];
            var random = new Random();
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for (int i = 0; i < stringChars.Length; i++) {
                stringChars[i] = chars[random.Next(chars.Length)];
            }
            string string1 = new string(stringChars);
            File.WriteAllText(@"C:'Top Folder'File Folder'file1.dat",
                string1);
            using(StreamReader sr = File.OpenText(@
                "C:'Top Folder'File Folder'file1.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine("file1.dat is a clean file");
                    Console.WriteLine("Path to file1.dat - {0}", path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            sequenceTwo: var stringChars2 = new char[26];
            var random2 = new Random();
            var chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZxxxxx";
            for (int i = 0; i < stringChars2.Length; i++) {
                stringChars2[i] = chars2[random2.Next(chars2.Length)];
            }
            string string2 = new string(stringChars2);
            string2 = string2.Replace("x", "'"VIRUS'"");
            File.WriteAllText(@"C:'Top Folder'File Folder'file2.dat",
                string2);
            using(StreamReader sr = File.OpenText(@
                "C:'Top Folder'FIle Folder'file2.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine(
                        "file2.dat is a HIGH THREAT virus file");
                    Console.WriteLine("Path to file2.dat - {0}'n",
                        path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            sequenceThree: var stringChars3 = new char[26];
            var random3 = new Random();
            var chars3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZx";
            for (int i = 0; i < stringChars3.Length; i++) {
                stringChars3[i] = chars3[random3.Next(chars3.Length)];
            }
            string string3 = new string(stringChars3);
            string3 = string3.Replace("x", "'"VIRUS'"");
            File.WriteAllText(@"C:'Top Folder'File Folder'file3.dat",
                string3);
            using(StreamReader sr = File.OpenText(@
                "C:'Top Folder'File Folder'file3.dat")) {
                string s = "";
                while ((s = sr.ReadLine()) != null) {
                    Console.WriteLine(s);
                    Console.WriteLine(
                        "file3.dat is a MODERATE THREAT virus file"
                    );
                    Console.WriteLine("Path to file3.dat - {0}'n",
                        path1);
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                goto end;
            }
            end: Console.WriteLine("'nDo you want to try again?Y/N");
            string end = Console.ReadLine();
            if (end == "Y" || end == "y") {
                Console.Clear();
                goto beginning;
            } else {
                Console.Clear();
                Console.WriteLine("Goodbye...Press any key to exit");
                Console.ReadKey();
            }
        }
    }
}

有没有办法在c#中缩短这段代码?

你的代码可以因为只是复制和粘贴,应该永远不是你首先想到要做什么,例如,这是你所做的一切,以生成一个字符串,所以你可以在每个序列中调用这个代码。

private string GenerateString(int idx)
{
    var stringChars = new char[26];
    var random = new Random();
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 0; i < stringChars.Length; i++) {
        stringChars[i] = chars[random.Next(chars.Length)];
    }
    return new string(stringChars);
}
//Example call (for sequence one) = string1 = GenerateString(1);

写入文件类似

private void WriteFile(int idx, string inputString ,string threatLevel)
{
    File.WriteAllText(@"C:'Top Folder'File Folder'file2.dat", inputString);
    string filePath = Path.Combine(@"C:'Top Folder'FIle Folder", 
                                     string.Format("file{0}.dat", idx));
    using(StreamReader sr = File.OpenText(filePath))
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) {
            Console.WriteLine(s);
            Console.WriteLine("file{0}.dat is a {1} file", idx, threatLevel);
            Console.WriteLine("Path to file{0}.dat - {1}'n", idx, filePath);
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}
//WriteToFile(1, string1, "clean");
//WriteToFile(2, string2, "HIGH THREAT virus");
//WriteToFile(3, string2, "MODERATE THREAT virus");

您应该查找switch语句,并找出一种方法来摆脱goto语句。