C#堆栈溢出状态

时间:2012-08-07 13:56:06

标签: c#

在我的基类中,其他人继承的基类具有以下属性:

private int DEFAULT_DISPLAY_ORDER = 999999;
private DateTime DEFAULT_DT = new DateTime(1111,1,1);

public int? Id {
    get 
    { 
        return Id.GetValueOrDefault(0);  
    }
    set 
    {
        if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
        Id = value;
    }
}
public String Description { get; set; }
public int? DisplayOrder { get; set; }

但是当我执行它时,我收到了这个错误:

+ $exception {
     Cannot evaluate expression because the current thread is in a stack 
     overflow state.}
     System.Exception {System.StackOverflowException}

在线

if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;

这到底是怎么回事?

6 个答案:

答案 0 :(得分:10)

看看这个:

public int? Id {
    get 
    { 
        return Id.GetValueOrDefault(0);  
    }

此处,访问Id要求您首先获取... Id。邦。

下一步:

set 
{
    if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
    Id = value;
}

看第二部分。要设置Id,您必须...为Id调用setter。邦。

你需要一个字段:

private int? id;

// Now use the field in the property bodies
public int? Id {
    get 
    { 
        return id.GetValueOrDefault(0);  
    }
    set 
    {
        if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
        id = value;
    }
}

答案 1 :(得分:3)

你从内部调用Id - 无限递归......不好:)

public int? Id {
    get 
    { 
        return Id.GetValueOrDefault(0); // This will keep calling the getter of Id. You need a backing field instead.
    }
    set 
    {
        if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
        Id = value; // And here...
    }
}

答案 2 :(得分:1)

ID = value将启动循环。你应该有一个像_id这样的私有变量,并在属性的setter和getter部分使用它。

答案 3 :(得分:1)

您正在创建一个无限循环,因为您在Id属性的get和set中引用了Id属性:P。所以,在获得,你得到了获得;)。在集合中,您将设置为设置。怪啊? :)

答案 4 :(得分:0)

Id = value;

这样做。您正在对同一属性内的属性进行递归赋值。

答案 5 :(得分:0)

当你拨打If时,它会一遍又一遍地递归调用Id。

return Id.GetValueOrDefault(0);
相关问题