类/打印到控制台中的哈希表

时间:2017-01-31 21:54:30

标签: c# class hashtable

我有一个对象类"字符"其中的哈希表用于武器。当我打印角色统计数据以供审批时,我只是试图将武器打印到控制台,但很难找到一种简单的方法来执行此操作。

Advs是Character对象数组,如果有任何我忘记包含的信息,请让我知道,第一次发布。我正在尝试修复i.weapons.value,其他所有内容都正确地打印到控制台,这给了我奇怪的值,看起来就像是打印时哈希表的指针。

    private static void ChStats(Character[] Advs) {
        foreach (Character i in Advs) {
            Console.WriteLine("Name: {0}\nClass: {1}\nLevel: {2}\nHealth: {3}\nStrength: {4}\nIntellect: {5}\nAgility: {6}\nSanity: {7}\nWeapon: {8}\n", 
                i.name, i.characterClass, i.lvl, i.hlth, i.str, i.itl, i.agi, i.san, i.weapons.value);
        }

作为补充,哈希表包含每个武器wNme和dmg的两个值。下面的代码有效,但看起来很草率,希望有更好的方法来实现这一点。

        foreach (Character i in Advs) {
            string[] weaponDesc = new string[10];
            int n = 0;
            foreach (Weapon w in i.weapons.Values)
            {
                weaponDesc[n++] = w.wNme;
            }
            // this version works but with extra commas
            //Console.WriteLine("Name: {0}\nClass: {1}\nLevel: {2}\nHealth: {3}\nStrength: {4}\nIntellect: {5}\nAgility: {6}\nSanity: {7}\nWeapon: {8}\n",
            //    i.name, i.characterClass, i.lvl, i.hlth, i.str, i.itl, i.agi, i.san, string.Join(", ",  weaponDesc));
            // better but more complex
            Console.WriteLine("Name: {0}\nClass: {1}\nLevel: {2}\nHealth: {3}\nStrength: {4}\nIntellect: {5}\nAgility: {6}\nSanity: {7}\nWeapon: {8}\n",
                i.name, i.characterClass, i.lvl, i.hlth, i.str, i.itl, i.agi, i.san, string.Join(", ",  weaponDesc.Where(s => !string.IsNullOrEmpty(s))));

1 个答案:

答案 0 :(得分:0)

泛型类型的HashSet类是更好的选择。

HashSet<Weapon> Weapons;
Weapons = new HashSet<Weapon>();
Weapons.Add(new Weapon()); // Assume this is created and populated elsewhere
StringBuilder SBText = new StringBuilder(64 + (Weapons.Count * 8)); // An approximation of the eventual string length
SBText.Append(@"Class, Level, etc...");
// Cryptic but compact Lync method (Not my favourite)
Weapons.Where(Wpn => !string.IsNullOrEmpty(Wpn.name)).ToList().ForEach(delegate (Weapon Wpn) { if (SBText.Length > 0) { SBText.Append(@", "); } SBText.Append(Wpn.name); });
// Explicit code method
foreach (Weapon Wpn in Weapons)
{
    if (!string.IsNullOrEmpty(Wpn.name))
    {
        if (SBText.Length > 0) { SBText.Append(@", "); }
        SBText.Append(Wpn.name);
    }
}
Console.WriteLine(SBText.ToString());