如何在课堂上使用字典

塔皮瓦

我如何使用文本框将项目添加到字典中,因为我在类中创建了字典,所以我在将字典链接到列表框时也遇到了问题,我如何alphabet从类调用到 Form1

我的课与字典

class MyCipher: ICipherDecipher
{
    private Dictionary<string, string> alphabet;

    public MyCipher()
    {
        alphabet = new Dictionary<string, string>();
        alphabet.Add("4", " take 4");
        alphabet.Add("3", " take 3");
        alphabet.Add("5d", " for 5 days");
    }
}

主要代码

public partial class Form1 : Form
{
    private ICipherDecipher myCipher;

    public Form1()
    {
        myCipher = new MyCipher();
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string textToBeCiphered = textBox1.Text;
        string textCiphered = myCipher.Cipher(textToBeCiphered, 6);
        textBox2.Text  = textCiphered;
    }
}

我如何将字典alphabet从我的类调用到 Form1 中的主代码,以便我可以在列表框属性中显示它?

安德鲁·亚瑟

将类型更改myCipherMyCipher

改变这一行:

private ICipherDecipher myCipher;

到这一行:

private MyCipher myCipher;

为字母表添加属性

改变这一行:

    private Dictionary<string, string> alphabet;

到这一行:

    public Dictionary<string, string> alphabet {get; set;}

然后你可以将它绑定到你的列表框:

listBox1.DataSource = new BindingSource(myCipher.alphabet, null);

根据字典设置 ListView(2 列):

        listView1.Items.Clear();
        listView1.Items.AddRange(myCipher.alphabet.Select(c => new ListViewItem
           (
             new string[] { c.Key, c.Value}
           )).ToArray());

根据字典设置 ListView(1 列):

listView1.Items.AddRange(myCipher.alphabet.Select(c => new ListViewItem(c.Key + " : " + c.Value)).ToArray());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章