代码之家  ›  专栏  ›  技术社区  ›  Hamza Waheed

关于C#中初始化构造函数中代码的最佳实践?关闭

  •  0
  • Hamza Waheed  · 技术社区  · 2 年前

    我正在学习C#并学习类,我有一个关于类初始化和构造函数的最佳实践的问题。

    例如,我在《玩家指南C#》中做了一个练习,这就是我最终得到的代码:

    internal class Arrows
    {
        /// <summary>
        /// Basic Practice class to ask for and define details of an arrow
        /// </summary>
        private enum _arrowhead
        {
            // Type of arrowhead
            Steel,
            Wood,
            Obsidian,
        }
    
        private enum _fletching
        {
            // Type of fletching
            Plastic,
            TurkeyFeathers,
            GooseFeathers,
        }
        
        private int _shaftLength = 60;   // default length of arrows is 60cm
        private float _shaftCostPerCm = 0.05f;
        private float _costOfArrow;
    
        public Arrows() {
            Console.WriteLine("Hello dear customer");
            Console.WriteLine("Welcome to my arrow shop\n");
            Console.WriteLine("First things first, what type of arrowhead would you like");
            foreach (string head in Enum.GetNames(typeof(_arrowhead))){
                Console.WriteLine(head + " = " + getHeadPrices(head) + " gold");
            }
            string _Head = Console.ReadLine();
    
            Console.WriteLine("\nTime now to select the type of fletching");
            foreach (string fletch in Enum.GetNames(typeof(_fletching)))
            {
                Console.WriteLine(fletch + " = " + getFletchingPrices(fletch) + " gold");
            }
            string _fletchingType = Console.ReadLine();
    
            Console.WriteLine("\nHow long do you want the arrows to be?");
            Console.WriteLine("I can manage to make arrows between 60 and 100 cm");
            _shaftLength = Convert.ToInt32(Console.ReadLine());
    
            _costOfArrow = singleArrowCost(_Head, _fletchingType, _shaftLength, _shaftCostPerCm);
            Console.WriteLine($"\nThe cost of one of these arrows is {_costOfArrow}");
        }
    

    我只想知道,在类外编写并提示用户完成所有这些操作,然后在构造函数中传递参数,或者将所有这些语句传递到构造函数内的控制台并相应地分配值,这是更好的做法吗。

    1 回复  |  直到 2 年前
        1
  •  2
  •   marsze    2 年前

    一定要在类之外获取所有输入,并将其作为参数传递。这是的原则 关注点分离。 它将使您的类更易于使用,并且从外部可以清楚地了解其意图。现在,一些使用构造函数的人不会知道所有控制台处理。而且如果你想从其他地方获得输入呢?

    构造函数应该只用于将对象初始化为可用状态,只执行所需的操作,并且理想情况下不会有任何副作用。

    一些小逻辑通常是好的(例如计算的属性)。对于更复杂的逻辑,可以考虑将私有构造函数与静态“工厂方法”结合使用。

    您可以阅读更多关于构造函数和最佳实践的信息 here .