C# Foreach 循环问题

3

我只是在用列表等进行实验的过程中编写了这个程序,我好奇为什么在foreach循环中Object总是显示为"Minecraft"愿望对象。这是因为它是最后一个被创建的Wish对象吗?我该如何修复它,使所有已声明的3个Wish对象都会显示出来呢? 谢谢!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Wish iPod = new Wish("iPod", "Various", 299.00);
            Wish Phone = new Wish("New Phone", "Various", 00.00);
            Wish Minecraft = new Wish("Minecraft Account", "www.minecraft.net", 30.00);

            List<Wish> Wishlist = new List<Wish>();
            Wishlist.Add(Phone);
            Wishlist.Add(iPod);
            Wishlist.Add(Minecraft);
            Console.WriteLine("Toby's Wishlist");
            Console.WriteLine("If cost is 00.00, the Wish's cost varies.");
            Console.WriteLine("              ");
            foreach (Wish wish in Wishlist)
            {
                Console.WriteLine("---Wish---");
                Console.WriteLine("Name: {0}", wish.getName());
                Console.WriteLine("Store: {0}", wish.getStore());
                Console.WriteLine("Cost: ${0}", wish.getCost().ToString());
                Console.WriteLine("----------");
                Console.WriteLine("           ");
            }
            Console.ReadLine();

        }
    }
    public class Wish
    {
        static string Name, Store;
        static double ApproxCost;
        public Wish(string name, string store, double approxCost)
        {
            Name = name;
            Store = store;
            ApproxCost = approxCost;
        }

        public string getName()
        {
            return Name;
        }
        public string getStore()
        {
            return Store;
        }
        public double getCost()
        {
            return ApproxCost;
        }
    }
}

1
你可能想考虑使用Decimal类型来表示成本,而不是使用Double - John Alexiou
2个回答

8

Wish 成员声明中的 static 删除。

static 表示数据将在所有实例之间共享。因此,static 成员也称为类变量。而非静态成员则是对象变量。


@TobyTurnerMay 如果这个答案是最有帮助的,请标记为已接受(即点击绿色复选框)吗?这有助于社区知道哪个答案实际上解决了问题,并奖励帮助您的人。 - Joshua Grosso Reinstate CMs

1

这是因为在Wish类中,您将Name、Score和ApproxCost声明为静态变量。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接