3

リストなどを実験するためにこのプログラムを作成していたところですが、foreach ループでオブジェクトが常に「Minecraft」の Wish オブジェクトとして表示される理由に興味がありました。作成された最後の 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;
        }
    }
}
4

2 に答える 2

8

メンバー宣言staticから削除Wish

staticデータがすべてのインスタンスで共有されることを意味します。そのstaticため、メンバーはクラス変数とも呼ばれます。静的メンバーではありませんが、オブジェクト変数です。

于 2012-11-18T00:13:23.337 に答える
1

これは、クラス Wish で、Name、Score、およびapproximateCost を static として宣言したためです。

于 2012-11-18T00:13:46.753 に答える