【发布时间】:2016-03-30 19:48:58
【问题描述】:
我一直在尝试的代码以及出了什么问题: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();
}
}
}
我一直在尝试自学 C#,但这一直困扰着我。我想制作一个接受字符串然后返回 Minion(新类)的字典。
一个 Minion 在创建时接受四个参数,因此在将其添加到字典之前,我必须专门编写一行代码来创建一个新的 Minion。
但是,当我检查我拥有的所有小兵时,出于某种原因,第一个小兵将其他小兵的属性还给我。
Wolfrider
Mana Cost: 1
Attack: 1
Health: 2
Taunt
Goldshire Footman
Mana Cost: 1
Attack: 1
Health: 2
Taunt
名单正常工作,因为名字是正确的......但狼骑兵具有金郡步兵的属性。
有没有更有效/优化的方法来做到这一点?如果没有,我做错了什么?
【问题讨论】:
标签: c# list class oop dictionary