C#中 ==运算符重载错误,怎么解决呢?
时间:2011-12-18
来源:互联网
[code=C#][/code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace HelloWordCsharp
{
public class my_List<T>
{
const int defaultCapacity = 4; //常量
T[] items;
int count; //字段
public static int changeCount = 0;
public static void ListChanged(object sender, EventArgs e)
{ changeCount++; }
public my_List(int capacity = defaultCapacity)
{
items = new T[capacity];
} //构造函数
public int Count
{
get { return count; }
}
public int Capacity
{ get {return items.Length; }
set {
if (value < count) value = count;
if (value != items.Length)
{
T[] newItems = new T[value];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
}
} //属性
public T this[int index]
{
get {
return items[index];
}
set {
items[index] = value;
OnChanged();
}
} //索引器
public void Add(T item)
{ if (count == Capacity) Capacity = count * 2;
items[count] = item;
count++;
OnChanged();
}
protected virtual void OnChanged()
{
if (Changed != null)
Changed(this, EventArgs.Empty);
}
public event EventHandler Changed; //事件
public override bool Equals(object other)
{
return Equals(this, other as my_List<T>);
}
public static bool Equals(my_List<T> a, my_List<T> b)
{
if (a == null) return b == null;
if (b == null || a.count != b.count) return false;
for (int i = 0; i < a.count; i++)
{ if (!object.Equals(a.items[i], b.items[i]))
{
return false;
}
}
return true;
}
public static bool operator ==(my_List<T> a, my_List<T> b)
{ return Equals(a, b); }
public static bool operator !=(my_List<T> a, my_List<T> b)
{ return !Equals(a, b); }
}
class Test{
static void Main() {
List<int> a = new List<int>();
a.Add(1);
a.Add(2);
List<int> b = new List<int>();
b.Add(1);
b.Add(2);
Console.WriteLine(a == b); // Outputs "True"
b.Add(3);
Console.WriteLine(a == b); // Outputs "False"
}
}
}
输出异常 为:Process is terminated due to StackOverflowException.
我调试时发现, 在 因为重载了 == ,所以 程序会在方法 operator ==(my_List<T> a, my_List<T> b) 和 public static bool Equals(my_List<T> a, my_List<T> b) 方法间不断相互调用.所以导致堆栈异常.
我挺纳闷,是我使用这个类出错,还是微软提供的文档的那个类不全或者是不对的呢?
另外我写的这个程序怎么才能修正这个错误呢?
作者: w731784510 发布时间: 2011-12-18
作者: bdmh 发布时间: 2011-12-18
重载和Equals中循环调用了,自己清理期中一个
作者: myhaikuotiankong 发布时间: 2011-12-18
作者: yxw545061402 发布时间: 2011-12-18
重载和Equals中循环调用了,自己清理期中一个
作者: w731784510 发布时间: 2011-12-18
我在 VS2010 里面运行,结果输出两个 False。没有任何异常!!!
作者: youzelin 发布时间: 2011-12-18
List是内置的容器 不能重定义的
LZ,你确定吗?
我在 VS2010 里面运行,结果输出两个 False。没有任何异常!!!
作者: w731784510 发布时间: 2011-12-18
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28