c# - 正确使用类?

标签 c# oop design-patterns class class-design

我是大学生(计算机科学专业),刚刚开始学习 C# 编程类(class)。 对于我们的作业,我一直在使用一个名为“显示”的类,我在其中放置可以在整个项目中多次使用的任何控制台输出。例如,请求继续或退出程序。我没有在 Main() 中多次输入它,而是从 Display 类中调用该方法。

高年级的另一位学生告诉我,我不应该这样做。这是糟糕的编码实践,我应该只在主类中包含所有方法(包含 Main()),并且只在绝对需要时才使用其他类。

我只是在寻找一些意见和建议。

我被要求包含代码。我本来打算,但不想让这篇文章太长。我选择了一项相当短的作业。我想澄清一下,我只是在学习,所以代码并不像你们许多人写的那么优雅。非常欢迎建设性的批评。

最终我只是在玩类的使用。我知道 Display 类中的一些方法可以很容易地放在 Main() 中。

这是包含 Main() 的 Program 类

namespace Chapter_6_10
{
class Program
{
    static void Main()
    {
        string triangle = "", result = " ";;
        char printingCharacter = ' ';
        int peakNumber = 0;
        Display.Instructions();
        Display.Continue();
        // perform a do... while loop to build triangle up to peak
        do
        {
            Console.Clear();
            Request.UserInput(out printingCharacter, out peakNumber);
            int  counter = 1, rowCounter = 0;
            do
            {
                do
                {
                    triangle += printingCharacter;
                    rowCounter++;
                }
                while (rowCounter < counter);
                counter++;
                rowCounter = 0;
                triangle += "\n";
            }
            while(counter != peakNumber);
            // perform a do... while loop to build triangle from peak to base
            do
            {
                do
                {
                    triangle += printingCharacter;
                    rowCounter++;
                }
                while (rowCounter < counter);
                counter--;
                rowCounter = 0;
                triangle += "\n";
            }
            while (counter != 0);
            Console.Clear();
            Console.WriteLine(triangle); // display triangle
            Display.DoAgain(out result); // see if user wants to do another or quit
            triangle = "";                
        }
        while (result != "q"); 
    }
}

这是显示类

namespace Chapter_6_10
{
// This class displays various outputs required by program
class Display
{
    // This method display the instructions for the user
    public static void Instructions()
    {
        Console.WriteLine("\nThis program will ask you to enter a character to be used "
            + " to create triangle."
            + "\nThen you will be asked to enter a number that will represent the"
            + "\ntriangles peak."
            + "\nAfter your values have been received a triangle will be drawn.");
    }
    // This method displays the choice to continue
    public static void Continue()
    {
        Console.WriteLine("\n\nPress the enter key when you are ready to continue...");
        Console.ReadLine();
    }
    // This method displays an error message
    public static void Error(string ErrorType)
    {
        Console.WriteLine("\nYou have entered \"{0}\", which is a value that is not valid!"
            + "\nThis is not rocket science."
            + "\n\nTry agian...", ErrorType);
    }
    // This method will ask user to press enter to do again or 'q' to quit
    public static void DoAgain(out string Result)
    {
        string input = " ";
        Console.WriteLine("\nPress enter to run program again"
            + "\nor type the letter 'q' to close the application.");
        input = Console.ReadLine();
        // convert input to lowercase so that only one test needed
        Result = input.ToLower();
    }        
}

这是请求类

namespace Chapter_6_10
{
// This class is used to get user input
class Request
{
    public static void UserInput(out char PrintingCharacter, out int PeakNumber)
    {
        string input = " ";
        char testCharacter = ' ';
        int testNumber = 0;

        // a do... while loop to get Printing Character from user
        // use TryParse() to test for correct input format
        do
        {
            Console.Write("\nPlease enter a character to be used to build triangle : ");
            input = Console.ReadLine();
            bool result = char.TryParse(input, out testCharacter);
            if (result)
            {

            }
            else
            {
                Console.Clear();
                Display.Error(input);
                input = " ";
            }
        }
        while (input == " ");
        // a do... while loop to get number from user
        // use TryParse() to test for correct input format
        do
        {
            Console.Write("\nPlease enter a number <between 1 and 10> for the peak of the triangle : ");
            input = Console.ReadLine();
            bool result = int.TryParse(input, out testNumber);
            if (result)
            {
                if ((testNumber > 0) && (testNumber < 11))
                {                        
                }
                else
                {
                    Console.Clear();
                    Display.Error(testNumber.ToString());
                    input = " ";
                }
            }
            else
            {
                Console.Clear();
                Display.Error(input);
                input = " ";
            }
        }
        while (input == " ");
        // assigned received values to 'outs' of method
        PrintingCharacter = testCharacter;
        PeakNumber = testNumber;
    }
}

就是这样。这会被认为是一种低效的编码方式吗?我该如何改进它?

感谢到目前为止的所有输入。这对我来说非常有值(value)。

最佳答案

一个彻底和精心设计的类结构对于遵守 object-oriented design 是极其重要的。原则。

以下是考虑将相关代码分解为单独类的几个原因:

  • 它创建了劳动分工并隔离了不同的任务。这有时被解释为 Single Responsibility Principle ,它说每个对象(类)都应该有单一的职责并专注于完成单一的任务。 Encapsulation在这里也很快成为一个重要的原则,基本上意味着数据与负责操作该数据的方法捆绑在一起。这也有助于减少错误潜入您的代码的机会。

  • 它可以帮助推广code reuse .与将代码分散在整个应用程序中相比,将现有类与您已经编写的代码集成到另一个应用程序中通常要容易得多。为什么要一遍又一遍地重写相同的代码?

  • 设计良好的类结构可以创建逻辑层次结构,使您的代码更易于理解和概念化,并使您的应用程序从长远来看更易于维护。这与我们将计算机上的文件组织到文件夹中以及我们生活中的其他一切(或至少我们尝试过)的原因相同。

关于c# - 正确使用类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237319/

相关文章:

c# - 打破 POCO 关系

c# - 从应用程序设置中定义的 KeyVault 检索 secret

C#:使方法的参数不可更改的最佳方法

java - 该解决方案的不同设计模式

c++ - 使用组合设计模式对不同类型的对象进行操作,有没有办法避免对一个对象进行多次操作?

c# - 命名空间和类名指南

c# - 如何在 LINQ 中选择多个表?

java - Java 中的访问修饰符(静态)

c++ - 派生的继承存储地址

Java Lambda : How it works in JVM & is it OOP?