【发布时间】:2017-02-28 04:35:03
【问题描述】:
我在 1 个文件中有这 2 个类
这个角色
public class Character{
public static int Count = 0;
public string username, charname;
public int gender, level, money, playtime;
public Character(string _username, string _charname, int _gender, int _level, int _money, int _playtime)
{
username = _username;
charname = _charname;
gender = _gender;
level = _level;
money = _money;
playtime = _playtime;
Count++;
}
}
还有这个播放器
public class Player : Script
{
public Dictionary<string, Character> CharacterList = new Dictionary<string, Character>();
}
我想从另一个文件中的另一个类中调用 CharacterList 字典,像这样
public class AmmuNation : Script
{
Player Ply = new Player();
public void Test(Client sender)
{
API.consoleOutput(Ply.CharacterList[sender.name].charname);
}
}
但是当 Test() 执行时,即使密钥在字典中,它也会给我这个错误
给定的键不在字典中。
在 System.Collections.Generic.Dictionary`2.get_Item(TKey key)
当我从 Player 类中调用它时它起作用了,并且会给我 charname 的值
但是当我从 AmmuNation 调用它时,它会说找不到密钥
当我尝试这个时,即使字典是空的
foreach (KeyValuePair<string, Character> kvp in Ply.CharacterList)
{
API.consoleOutput(kvp.Key);
}
但在 Player 上,它会打印 CharacterList
中的每个 Key【问题讨论】:
-
您在
AmmuNation中创建了一个新的Player对象,并且该对象拥有自己的字典。如果要在两个地方使用相同的 Dictionary,则需要在两个地方使用相同的Player对象。或将CharacterList设为静态。东西。 -
@itsme86 当我将 CharacterList 设为静态时,它说无法通过实例引用访问;用类型名称限定它是什么意思,我是 OOP 的新手对不起
-
你是如何在
Player类中填充字典的?你怎么称呼它在课堂上Player?Player构造函数中传入的参数Client sender的作用是什么? -
@ChetanRanpariya 我正在使用 Add() 在 Player 类中添加字典,我直接调用它是因为它是 Player 类的属性,“Client sender”只是另一个包含变量的类“ name”,所以我可以使用“sender.name”获取字典键
-
在您尝试在测试方法中访问字典之前,字典填充代码也会被执行?能分享一下字典人口的代码,以及在播放器和AmmuNation类测试方法中的使用情况吗?
标签: c# class dictionary