首页 > 解决方案 > C# OOP 中的构造函数

问题描述

此类的构造函数应生成关于随机选择的人的随机提示,并将提示存储在它的随机提示属性中。看来我的两个构造函数都有问题,但我不知道如何解决这个问题或问题是什么。请问有什么想法吗?

 class RandomHintGame : Game
    {
        string randomHint;
        static Random r = new Random();

        // Constructor 1
        public RandomHintGame(string randomHint, Person person) : base(person)
        {
            this.randomHint = randomHint;
        }
        
        // Constructor 2
        public RandomHintGame(Person person) : this(person)
        {
            int randomNumber = r.Next(0, 3);

            switch (randomNumber)
            {
                case 0: randomHint = $"The person {HasHat} a hat."; break;
                case 1: randomHint = $"The person has {EyeColor} eyes."; break;
                case 2: randomHint = $"The person is a {Gender}"; break;
            }
        }
    }

标签: c#oopconstructor

解决方案


int randomNumber = r.Next(0, 3);

将返回 0,1,2 查看链接

你的开关是1,2,3

而构造函数 2 的基础不是这个

// Constructor 2
 public RandomHintGame(Person person) : base(person)

推荐阅读