1

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

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;

这到底是怎么回事?

4

6 回答 6

10

看这个:

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

在这里,访问Id需要您首先获取Id...。砰。

下一个:

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

看第二部分。为了设置Id,你必须...调用设置器Id。砰。

您需要一个字段:

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;
    }
}
于 2012-08-07T13:59:00.517 回答
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...
    }
}
于 2012-08-07T13:58:29.887 回答
1

ID = value将引发一个循环。您应该有一个私有变量_id,并在属性的 setter 和 getter 部分中使用它。

于 2012-08-07T13:58:33.843 回答
1

You're creating a infinite loop, because you are referring to Id property in get and set of the Id property :P. So in get, you are getting to get the getting ;). And in the set, you are setting to set the setting. Weird huh? :)

于 2012-08-07T14:00:21.430 回答
0
Id = value;

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

于 2012-08-07T13:59:16.557 回答
0

当您调用 Id 时,它会一遍又一遍地再次递归调用 Id。

return Id.GetValueOrDefault(0);
于 2012-08-07T13:59:44.417 回答