简体   繁体   中英

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. 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? 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

static means that the data will be shared across all the instances. So static members are also so called class variables. While not static members - are object variables.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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