尝试将公共值分配给私有支持字段时发生StackOverflowException

时间:2014-03-13 18:59:04

标签: c# .net

我有一个私人支持者的公共财产,如下所示。在selected = Selected;行上,我收到了SO异常。似乎赋值会导致一些无限递归。有人可以更详细地解释发生了什么吗?代码应该是什么?

    //other class stuff AssetTypes is an enum btw.
    private AssetTypes? selected = null;

    public AssetTypes? Selected
    {
        get
        {
            return selected;
        }
        set
        {
            selected = Selected;

            if (selected == AssetTypes.Image)
            {
                image.Click();
            }
            else if (selected == AssetTypes.Video)
            {
                video.Click();
            }
            else
            {
                selected = null;
            }
        }
    }

唯一可以更改的部分是setter中的赋值。 if-else逻辑需要不受影响。

4 个答案:

答案 0 :(得分:3)

setter有一个名为value的参数,该参数是属性设置的值。您应该从中获取新值,而不是从Selected获取新值,该值仅调用getter,后者返回先前的值。

因此,这条线没有任何作用:

selected = Selected;

你永远不应该从它自己的setter中分配Selected,因为它会调用相同的setter,因此你的无限递归。

请改为尝试:

set
{        
    if (value == AssetTypes.Image)
    {
        image.Click();
        selected = value;
    }
    else if (value == AssetTypes.Video)
    {
        video.Click();
        selected = value;
    }
    else
    {
        selected = null;
    }
}

答案 1 :(得分:1)

你在Selected = null上有一个无限递归,这就是你得到一个stackoverflow异常的原因。它会一遍又一遍地调用Selected,直到最后爆发异常。

改变它
selected = null;

答案 2 :(得分:1)

我认为问题出在其他地方:Selected = null

selected = null与小写s一起使用。

问候!

答案 3 :(得分:1)

selected =选择无效

传递给Set的是值;

public AssetTypes? Selected
{
    get
    {
        return selected;
    }
    set
    {
        if (selected == value) return;  // use this to not do it again

        selected = value;

        if (selected == AssetTypes.Image)
        {
            image.Click();
        }
        else if (selected == AssetTypes.Video)
        {
            video.Click();
        }
        else
        {
            selected = null;   // Selected = null; was the recursion
        }
        NotifyPropertyChanged("Selected");  // this optional and only if you implement INPC
    }
}