我在c#中创建了这个程序,它实现了IComparable接口来比较车辆名称并按字母顺序排序。代码编译成功但执行时却给了我StackOverFlowExecption。这是我的代码 -
class Vehicle:IComparable
{
private string vehiclename
{
get
{ return vehiclename;
}
set
{
vehiclename = value;
}
}
public Vehicle(string name)
{
vehiclename = name;
}
int IComparable.CompareTo(Object obj)
{
Vehicle temp = (Vehicle)obj;
return string.Compare(this.vehiclename, temp.vehiclename);
}
static void Main(string[] args)
{
Vehicle[] myvehicles = new Vehicle[5];
myvehicles[0] = new Vehicle("Honda City");
myvehicles[1] = new Vehicle("Nano");
myvehicles[2] = new Vehicle("Desire");
myvehicles[3] = new Vehicle("Santro");
myvehicles[4] = new Vehicle("Nissan");
Console.WriteLine("Unordered List of vehicles:");
foreach (Vehicle v in myvehicles)
Console.WriteLine(myvehicles);
Array.Sort(myvehicles);
Console.WriteLine("ordered List of vehicles:");
foreach (Vehicle v in myvehicles)
Console.WriteLine(myvehicles);
}
}
此异常的原因是什么?如何解决?
答案 0 :(得分:2)
private string vehiclename
{
get
{
return vehiclename;
}
set
{
vehiclename = value;
}
}
您正在使用此代码创建循环!
当您为属性vehiclename设置值时,“value”被分配给vehiclename,“value”被分配给vehiclename,“value”被分配给vehiclename ...
可以通过重命名属性来解决这个问题:
private string Vehiclename
{
get
{
return vehiclename;
}
set
{
vehiclename = value;
}
}
string vehiclename = string.Empty;
答案 1 :(得分:2)
您的get
和set
会自行调用:
private string vehiclename
{
get
{ return vehiclename;
}
set
{
vehiclename = value;
}
}
因此,访问此属性(对于get
或set
)将导致发生溢出。
我怀疑你要么auto-implemented property:
private string vehiclename
{
get;
set;
}
或者提供您自己的支持字段:
private string _vehiclename;
private string vehiclename
{
get
{ return _vehiclename;
}
set
{
_vehiclename = value;
}
}
或者,您可能根本不想要属性(private
属性非常罕见)并且只想要一个字段:
private string vehiclename;
答案 2 :(得分:0)
您的属性导致堆栈溢出异常。让我们来看看:
private string vehiclename
{
get
{ return vehiclename;
}
set
{
vehiclename = value;
}
}
在调用vehiclename的setter时,它会将值分配给调用setter的属性vehiclename ....这当然是堆栈溢出。使用属性时,您应该坚持使用自动实现的属性或有效的支持字段。