1

我在 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);

    }
}

此异常的原因是什么,我该如何解决?

4

3 回答 3

2
private string vehiclename 
    { 
        get 
        { 
            return vehiclename; 
        }
        set
        {
            vehiclename = value;
        }
    }

您正在使用此代码创建一个循环!

当您为属性车辆名称设置值时,“值”被分配给车辆名称,“值”被分配给车辆名称,“值”被分配给车辆名称......

这可以通过像这样重命名属性来解决:

     private string Vehiclename 
            { 
                get 
                { 
                    return vehiclename; 
                }
                set
                {
                    vehiclename = value;
                }
            }
    string vehiclename = string.Empty;
于 2013-10-16T06:50:54.387 回答
2

getset调用自己:

private string vehiclename 
{ 
    get 
    { return vehiclename; 
    }
    set
    {
        vehiclename = value;
    }
}

所以访问这个属性(for getor set)会导致溢出发生。

我怀疑您要么想要一个自动实现的属性

private string vehiclename 
{ 
    get;
    set;
}

或者提供您自己的支持字段:

private string _vehiclename;
private string vehiclename 
{ 
    get 
    { return _vehiclename; 
    }
    set
    {
        _vehiclename = value;
    }
}

或者,您可能根本不想要一个属性(private属性非常罕见)而只想要一个字段:

private string vehiclename;
于 2013-10-16T06:50:55.460 回答
0

您的属性导致堆栈溢出异常。我们来看一下:

private string vehiclename 
{ 
    get 
    { return vehiclename; 
    }
    set
    {
        vehiclename = value;
    }
}

在调用vehiclename 的setter 时,它会将值分配给调用setter 的属性vehiclename ...。这当然是堆栈溢出。使用属性时,您应该坚持使用自动实现的属性或有效的支持字段。

于 2013-10-16T06:51:54.350 回答