简体   繁体   English

C#Foreach循环问题

[英]C# Foreach Loop Issue

I was just making this program to experiment with lists and such, and I was curious as to why in the foreach loop the Object always shows up as the "Minecraft" Wish object. 我只是让这个程序试验列表等等,我很好奇为什么在foreach循环中Object始终显示为“Minecraft”Wish对象。 Is it because it was the last Wish object to be created? 是因为它是最后创建的愿望对象吗? And how can I fix it, so all 3 Wish objects which have been declared show up? 我怎么能修复它,所以已宣布的所有3个Wish对象都出现了? Thanks! 谢谢!


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;
        }
    }
}

Remove static from Wish members declaration Wish成员声明中删除static

static means that the data will be shared across all the instances. static表示将在所有实例之间共享数据。 So static members are also so called class variables. 所以static成员也称为类变量。 While not static members - are object variables. 虽然不是静态成员 - 是对象变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM