第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

無(wú)法從類內(nèi)將項(xiàng)目添加到字典中

無(wú)法從類內(nèi)將項(xiàng)目添加到字典中

C#
開滿天機(jī) 2023-12-17 20:04:36
我正在開展一個(gè)學(xué)習(xí)項(xiàng)目,試圖在其中學(xué)習(xí)更好的實(shí)踐。我有一個(gè)類,Player,除了其他之外,播放器還有 Dictionary 稱為 Items,可以在其中存儲(chǔ)項(xiàng)目。 Player 僅使用 Name 和 Age 進(jìn)行初始化,字典在 Player 初始化時(shí)應(yīng)該為空。除了故事之外,玩家還可以獲取將存儲(chǔ)在庫(kù)存中的物品,因此我嘗試創(chuàng)建一個(gè)可以調(diào)用的方法來(lái)執(zhí)行此操作,但是我面臨以下問(wèn)題:如果該方法不是靜態(tài)的,則無(wú)法從類外部調(diào)用它,并出現(xiàn)以下錯(cuò)誤:An object reference is required for the non-static field, method, or property 'Player.AddItems(int, string)'。如果方法是靜態(tài)的,則不會(huì)看到Items 字典,并出現(xiàn)以下錯(cuò)誤:An object reference is required for the non-static field, method, or property 'Player.Items'。我試圖從主函數(shù)(稍后將成為一個(gè)類)中調(diào)用它:Player.AddItems(0, "Wallet");。任何建議表示贊賞。class Player    {        public string Name { get; set; }        public int Age { get; set; }        public Dictionary<int, string> Items { get; set; }        public float Damage { get; set; }        public float Health { get; set; }        public Player(string Name, int Age)        {            this.Name = Name;            this.Age = Age;            this.Items = new Dictionary<int, string>();            this.Damage = 0;            this.Health = 20;        }        public void AddItems(int key, string item)        {            this.Items.Add(key, item);        }    }
查看完整描述

1 回答

?
紅糖糍粑

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個(gè)贊

非靜態(tài)字段、方法或需要對(duì)象引用 屬性“Player.AddItems(int, string)”


您需要先創(chuàng)建一個(gè)對(duì)象才能調(diào)用類的非靜態(tài)方法。


Player p = new Player("John", "25");

p.AddItems(1, "Data");

非靜態(tài)字段、方法或需要對(duì)象引用 屬性“Player.Items”。


您無(wú)法從靜態(tài)方法訪問(wèn)非靜態(tài)成員


PS:您可以直接為屬性分配默認(rèn)值。


class Player

{

    public Player(string Name, int Age) : this()

    {

        this.Name = Name;

        this.Age = Age;

    }


    public string Name { get; set; }


    public int Age { get; set; }


    public Dictionary<int, string> Items { get; set; } = new Dictionary<int, string>();


    public float Health { get; set; } = 20;


    public float Damage { get; set; }


    public void AddItems(int key, string item)

    {

        this.Items.Add(key, item);

    }


}


查看完整回答
反對(duì) 回復(fù) 2023-12-17
  • 1 回答
  • 0 關(guān)注
  • 194 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)