欢迎光临

木子屋

标题: 让C#类支持关联数组

作者: dnawo

日期: 2010-01-05 10:31 AM

分类: Web编程

内容: 复制内容到剪贴板 程序代码using System;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass();
//添加遍历
t["aaa"] = "111";
t["bbb"] = "222";
t["ccc"] = "333";
foreach (string item in t)
{
Console.WriteLine(item + "=" + t[item]);
}
//删除再遍历
t["bbb"] = null;
foreach (string item in t)
{
Console.WriteLine(item + "=" + t[item]);
}
Console.ReadKey();
}
}
/// <summary>
/// 实现关联数组的类
/// </summary>
class TestClass : IEnumerable, IEnumerator
{
Dictionary<string, string> _dict = new Dictionary<string, string>();
List<string> _list = new List<string>();
public TestClass()
{ }
public string this[string name]
{
get
{
if (_dict.ContainsKey(name))
return _dict[name];
else
return string.Empty;
}
set
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("键不能为空。");
else
{
if (!_dict.ContainsKey(name))
{
_dict.Add(name, value);
_list.Add(name);
}
else
{
if (value == null || string.IsNullOrEmpty(value)) //值为空时删除
{
_dict.Remove(name);
_list.Remove(name);
}
else
{
_dict[name] = value;
}
}
}
}
}
//IEnumerable实现部分
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
//IEnumerator实现部分
private int position = -1;
public bool MoveNext()
{
position++;
if (position < _list.Count)
return true;
else
{
Reset();
return false;
}
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
try
{
return _list[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.055 ms

返回

标题: 让C#类支持关联数组

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.055 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 2.117 ms

返回