您的位置:首页 > 其它

运算符重载 hash原理 Equals方法

2014-01-28 13:21 351 查看
重载的方法提供转换的实现

->定义隐式转换使用关键字 implicit

->定义显式转换使用关键字 explicit

->转换顺序与定义顺序相同

->变量1=变量2 对应参数 类型1(类型2 value)

->语法:

[访问修饰符] static[implicit[explicit]] Operator 目标类型(待转换类型 value)

{

  目标类型 0=new 目标类型();

  //赋值操作,显示操作可以将赋值操作用checked{}块包起来,如放不下,就异常

  return 0;

}

class Program
{
static void Main(string[] args)
{
Person p = new Person();
Person p1 = new Person();
p1.Age = 25;
p.Age = 34;
int num1 = p;
int num2 = p + p1;

}
}
class Person
{
public int Age
{
set;
get;
}
public static implicit operator int(Person p){
return p.Age;
}
public static int operator +(Person p1, Person p2)
{
return p1.Age + p2.Age;
}
}


string字符串

string的常用方法前面博客已有记载,此处补充说明,string类的比较方法

-》==单个字符进行比较

-》Equal() 可以进行控制的比较。

  bool <object>.Equals(object o);

   bool<string>.Equals(string str);

   bool string.Equals(string str1,string str2)

   int string.Compare(string str1,string str2);

protected class ZQIEnumerator : IEnumerator  //封装一个类,用老作为枚举器,实现接口IEnumerator的所有成员
{
//int currentIndex = -1;
int currentIndex;
ArrayList list;
public ZQIEnumerator(ArrayList obj)
{
this.list = obj;
currentIndex = list.Count;
}
public object Current
{
get { return list[currentIndex]; }
}
public bool MoveNext()
{
currentIndex--;
return currentIndex >=0;
}
public void Reset()
{
throw new NotImplementedException();
}
}


View Code



既然我们知道使用foreach遍历集合的原理了,那么我们就很容易理解以下方式也可以实现遍历

Hashtable hs = new Hashtable();
for(int i = 0; i < 10;i++ )
{
hs.Add(i, i * 11);
}
var item=hs.GetEnumerator();
while(item.MoveNext())
{
DictionaryEntry de = (DictionaryEntry)item.Current;
Console.WriteLine(de.Key + "-" + de.Value);
}


或者用for循环遍历

Hashtable hs = new Hashtable();
for (int i = 0; i < 10;i++ )
{
  hs.Add(i, i * 11);
}
var item=hs.GetEnumerator();
for (; item.MoveNext(); )
{
DictionaryEntry de1 = (DictionaryEntry)item.Current;
Console.WriteLine(de1.Key + "---" + de1.Value);
}


泛型集合Dictionary与List /article/5929862.html

其他泛型集合:因其他一般泛型集合都可以用Dictionary或List代替,所以便不一一做介绍

其中,Hashset<T> hash集,表示所有数字不重复的集合

int[] nums = { 1, 2, 3, 4, 2, 1, 3, 6, 8 };
HashSet<int> hs = new HashSet<int>(nums);//结果为1,2,3,4,6,8
nums= hs.ToArray();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: