StackOverflowException的原因是什么,如何解决

本文关键字:何解决 解决 是什么 StackOverflowException | 更新日期: 2023-09-27 18:35:44

我用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);
    }
}

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

StackOverflowException的原因是什么,如何解决

您的getset调用自己:

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

因此,访问此属性(对于getset)将导致发生溢出。

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

private string vehiclename 
{ 
    get;
    set;
}

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

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

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

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

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

当您为属性车辆名称设置值时,"值"分配给车辆名称,"值"

分配给车辆名称,"值"分配给车辆名称...

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

     private string Vehiclename 
            { 
                get 
                { 
                    return vehiclename; 
                }
                set
                {
                    vehiclename = value;
                }
            }
    string vehiclename = string.Empty;

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

private string vehiclename 
{ 
    get 
    { return vehiclename; 
    }
    set
    {
        vehiclename = value;
    }
}
在调用车辆名称的设置器

时,它将值分配给调用设置器的属性车辆名称....这当然是堆栈溢出。使用属性时,应坚持使用自动实现的属性或有效的支持字段。