c# - StackOverflowException 的原因是什么,如何解决?

标签 c# visual-studio-2010 visual-studio c#-3.0

<分区>

我用 c# 编写了这个程序,它实现了 IComparable 接口(interface)来比较车辆的名称并按字母顺序对它们进行排序。代码编译成功但在执行它时给了我 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);

    }
}

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

最佳答案

您的 getset 调用它们自己:

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

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

我怀疑你想要一个 auto-implemented property :

private string vehiclename 
{ 
    get;
    set;
}

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

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

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

private string vehiclename;

关于c# - StackOverflowException 的原因是什么,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19396877/

相关文章:

c# - 存储抓取数据的最简单方法

visual-studio-2010 - 在 "Go to Definition"之后,是否有返回到原来位置的命令?

visual-studio - Visual Studio 中的 ExtJS (2010)

c# - Microsoft.VisualStudio.TeamFoundation 引用在哪里?

c# - 为 Log4Net 中的特定异常设置日志记录级别(对于 Episerver)

c# - Fluent 和 NHibernate 的泛型

c# - 导入 pdf 中的指定目的地

c++ - 在 Visual Studios 2010 的外部依赖文件夹中搜索文本/代码

c# - 无法在 Windows 窗体设计器上使用鼠标移动控件

c# - 单元测试在 Thread.Sleep 时间之前完成