首页 > 解决方案 > 输出不是它应该是的

问题描述

using System;

public class Program
{   
    
        public class toy
        {
            string name = "";
            double price = 0;
            
            public string getName()
            {
                return name;
            }
            
            public double getPrice()
            {
                return price;
            }
            
            public void setName(string Name)
            {
                name = Name;
            }
            
            public void setPrice(double Price)
            {
                price = Price;
            }
            
            static void Main()
                
                
    {
            
            
            toy toy1 =new toy();
            toy1.setName("Car");
            toy1.setPrice(10);
            
            toy toy2 =new toy();
            toy2.setName("Soldier");
            toy2.setPrice(15);
            
            Console.WriteLine(toy1);
            Console.WriteLine(toy2);
                        
            
        }
    }
}

大家好。我是编程新手。我在这里做错了什么?输出显示“程序+玩具程序+玩具”

我希望它像“Car 10 Soldier 15”

标签: c#

解决方案


你应该特别注意乔恩的建议。此外,命名空间也很重要。

PS如果你想要真相,我不会回答这样一个草率的问题,但即使是乔恩也对此感兴趣......请多加注意。

using System;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {

            var toy1 = new Toy { Name = "Car", Price = 10 };
            var toy2 = new Toy { Name = "Soldier", Price = 15 };

            Console.Write(toy1);
            Console.Write(toy2);

            Console.Read();
        }
    }    

    class Toy {
        public string Name { get; set; } = "";
        public double Price { get; set; } = 0;//This is pointless because of its default value is already 0

        public override string ToString() => $" {Name} {Price}";
    }
}

推荐阅读