出于争论的目的,这是我们的设计目标:我们有一个"怪物"对象,而"怪物"将有几个"权力".用户通过ListView项与权限交互.
首先,我们创建一个Power对象.为对象提供以下方法:
public ListViewItem makeKey()
{
return new ListViewItem(name);
}
Run Code Online (Sandbox Code Playgroud)
其中name是电源的名称和字符串.此ListViewItem将作为键,允许我们稍后识别和检索此功能.
接下来,我们需要在Monster对象中添加一些内容来跟踪所有这些功能.
public Dictionary<ListViewItem,Power> powers;
Run Code Online (Sandbox Code Playgroud)
所以现在我们需要一种方法来增加怪物的力量.
public void addPower(Power newPower) {
ListViewItem key = newPower.makeKey();
monster.powers.add(key, newPower);
}
Run Code Online (Sandbox Code Playgroud)
好的,差不多完成了!现在我们有了ListViewItems的字典,它与怪物的力量有关.只需从该字典中获取密钥并将其粘贴到ListView中:
foreach (ListViewItem key in powers.Keys)
powerList.Items.Add(key);
Run Code Online (Sandbox Code Playgroud)
其中powerList是ListView,我们将ListViewItems添加到.
好的,所以我们在ListView中得到了ListViewItems!现在,我们如何与这些互动?做一个按钮,然后是一个像这样的函数:
private void powerRemoveButton_Click(object sender, EventArgs e)
{
if (powerList.SelectedIndices.Count > 0)
{
int n = powerList.SelectedIndices[0];
ListViewItem key = powerList.Items[n];
monster.powers.Remove(key);
powerList.Items.Remove(key);
}
else
{
MessageBox.Show("No power selected.");
}
}
Run Code Online (Sandbox Code Playgroud)
就是这样.我希望你发现这很有帮助.我不确定这是否是他们设计的一个有意义的方面,但当你使用ListViewItem作为关键时,ListViews和Dictionaries非常好地融合在一起,这是一种快乐!
| 归档时间: |
|
| 查看次数: |
4688 次 |
| 最近记录: |