Cis*_*ega 4 c# oop dictionary class list
我一直在尝试的代码和出了什么问题:http://ideone.com/cvLRLg
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Minion
{
public static int manaCost;
public static int attack;
public static int health;
public static string cardText;
public Minion(int mana, int atk, int h, string txt)
{
manaCost = mana;
attack = atk;
health = h;
cardText = txt;
}
public void displayStats(string name)
{
Console.WriteLine(name + "\nMana Cost: " + manaCost + "\nAttack: " + attack + "\nHealth: " + health + "\n" + cardText + "\n");
}
}
class Program
{
static void Main(string[] args)
{
List<string> indexList = new List<string>();
Dictionary<string, Minion> minionList = new Dictionary<string, Minion>();
//buffer so I start at 1 and not 0
indexList.Add("MissingNo");
//make a Wolfrider card
indexList.Add("Wolfrider");
Minion Wolfrider = new Minion(3, 3, 1, "Charge");
minionList.Add(indexList[1], Wolfrider);
//make a Goldshire Footman card
indexList.Add("Goldshire Footman");
Minion GoldshireFootman = new Minion(1, 1, 2, "Taunt");
minionList.Add(indexList[2], GoldshireFootman);
//look through all my cards
for (int i = 1; i < indexList.Count(); i++)
minionList[indexList[i]].displayStats(indexList[i]);
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我一直在努力教自己C#,但这一直困扰着我.我想创建一个接受字符串的Dictionary然后返回一个Minion(新类).
Minion在制作时会接受四个参数,因此我必须专门用一行代码来制作一个新的Minion,然后将其添加到Dictionary中.
然而,当我经历我拥有的所有Minions时,由于某种原因,第一个让我回到OTHER Minion的属性.
Wolfrider
Mana Cost: 1
Attack: 1
Health: 2
Taunt
Goldshire Footman
Mana Cost: 1
Attack: 1
Health: 2
Taunt
Run Code Online (Sandbox Code Playgroud)
列表工作正常,因为名称是正确的......但Wolfrider具有Goldshire Footman的属性.
有没有更有效/优化的方法来做到这一点?如果没有,我做错了什么?
主要问题是您的成员是static:
public static int manaCost
Run Code Online (Sandbox Code Playgroud)
所以基本上,你影响的最后一个值获胜.将它们转换为实例属性:
public int ManaCost { get; set; }
Run Code Online (Sandbox Code Playgroud)
然后摆脱indexList并直接使用你的Minion的名字作为字典键.
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |