C#Foreach循环问题

时间:2012-11-18 00:09:10

标签: c#

我只是让这个程序试验列表等等,我很好奇为什么在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;
        }
    }
}

2 个答案:

答案 0 :(得分:8)

static成员声明

中删除Wish

static表示将在所有实例之间共享数据。所以static成员也称为类变量。虽然不是静态成员 - 是对象变量。

答案 1 :(得分:1)

这是因为在课堂上希望你将Name,Score和ApproxCost声明为静态。

相关问题