halcom中国吧 关注:11贴子:147
  • 0回复贴,共1

C#字典重写

只看楼主收藏回复

using ConsoleApp1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
MyDictionary<string, int> myDictionary = new MyDictionary<string, int>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myDictionary.Add("apple", 1);
myDictionary["banana"] = 2;
}
private void button2_Click(object sender, EventArgs e)
{
myDictionary.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
myDictionary["banana"] = 2;
myDictionary.Add("banana", 1);
myDictionary.Add("banana", 10);
int x = 0;
}
}
}
字典DLL库为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class MyDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> _dictionary = new Dictionary<TKey, TValue>();
public void Add(TKey key, TValue value)
{
if (_dictionary.ContainsKey(key))
{
_dictionary[key] = value;
}
else
{
_dictionary.Add(key, value);
}
}
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
public bool Remove(TKey key)
{
return _dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dictionary.TryGetValue(key, out value);
}
public void Clear()
{
_dictionary.Clear();
}
public int Count => _dictionary.Count;
public IEnumerable<TKey> Keys => _dictionary.Keys;
public IEnumerable<TValue> Values => _dictionary.Values;
public TValue this[TKey key]
{
get => _dictionary[key];
set => _dictionary[key] = value;
}
}
}


IP属地:广东1楼2024-05-13 22:15回复