C#中的堆栈溢出错误-但如何解决? [英] Stack overflow error in C# - but how to fix it?

查看:147
本文介绍了C#中的堆栈溢出错误-但如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常有趣的运行时错误,该错误会导致流氓堆栈溢出.

I've run into a really interesting runtime bug which generates a rogue stack overflow.

我定义的结构如下:

public enum EnumDataType { Raspberry, Orange, Pear, Apple };

public class DataRequest
{
    public long DataSize 
    { 
        get { return 0; } 
        set { DataSize = value; } 
    }

    public EnumDataType DataType  
    { 
        get { return EnumDataType.Apple; } 
        set { DataType = value; } 
    }
}

以下几行很完美:

DataRequest request = new DataRequest();
request.DataSize = 60;

但是,当我跳过代码中的以下行时,它会产生堆栈溢出:

However, when I step over the following line in code, it generates a stack overflow:

request.DataType = EnumDataType.Raspberry;

当然,我可以通过删除默认值或使用自动获取/设置来修复它,但是我需要它既可读又可写,并返回默认值-有什么想法吗?

Of course, I can fix it by removing the defaults, or using auto get/set, but I need it to be both readable and writable, and return a default - any ideas?

推荐答案

正如其他人所说,由于您的属性设置程序只是在调用自身,所以发生了堆栈溢出.如果您将其视为一种方法,可能会更容易理解:

As others have said, the stack overflow occurs because your property setter is just calling itself. It may be simpler to understand if you think of it as a method:

// This obviously recurses until it blows up
public void SetDataType(long value)
{
    SetDataType(value);
}

据我了解,您正在尝试创建普通属性,但使用默认值,对吧?

As I understand it, you're trying to create normal properties but with a default value, right?

在这种情况下,您需要支持由setter设置的变量-并且getter也应该返回这些变量.这是变量,应获取默认值:

In that case, you need backing variables which are set by the setters - and the getters should return those variables, too. It's the variables which should get default values:

private long dataSize = 0;
public long DataSize {
  get { return dataSize; }
  set { dataSize = value; }
}

private EnumDataType dataType = EnumDataType.Apple;
public EnumDataType DataType { 
  get { return dataType; }
  set { dataType = value; }
}

或者,使用自动属性,但在构造函数中设置默认值:

Alternatively, use automatic properties but set the defaults in your constructor:

public long DataSize { get; set; }
public EnumDataType DataType { get; set; }

public DataRequest()
{
    DataSize = 0; // Not really required; default anyway
    DataType = EnumDataType.Apple;
}

这篇关于C#中的堆栈溢出错误-但如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆