【问题标题】:This simple user control code crashes VS2015. Have no idea why这个简单的用户控制代码会导致 VS2015 崩溃。不知道为什么
【发布时间】:2017-07-01 23:44:02
【问题描述】:
public partial class displayvoltage : UserControl
{
    public displayvoltage()
    {
        InitializeComponent();
        if (!this.ratio_1.Checked && !this.ratio_12.Checked && !this.ratio_34.Checked && !this.ratio_14.Checked)
            this.ratio_1.Checked = true;
    }

    public double Ratio
    {
        get
        {
            if (this.ratio_1.Checked) return 1.0;
            if (this.ratio_1.Checked) return 4.0 / 3.0;
            if (this.ratio_1.Checked) return 2.0;
            return 4.0;
        }
    }

    public int SetRatio
    {
        set
        {
            if (value == 1) this.ratio_1.Checked = true;
            if (value == 2) this.ratio_34.Checked = true;
            if (value == 3) this.ratio_12.Checked = true;
            if (value == 4) this.ratio_14.Checked = true;
            SetRatio = value;
        }
    }

    [DefaultValue(0.0)]
    public double Voltage
    {
        get { return Voltage * this.Ratio; }
        set { Voltage = value; }
    }

    private bool DisplayVoltage = false;
    private bool Pause = false;

    private void ratio_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton r = (RadioButton)sender;

        if (r.Checked) Invalidate();
    }
}

由设计师创建,只有 4 个收音机和一个面板。 即使我想显示控件 VS 崩溃的属性,如果我启动程序它也会崩溃。可能是什么问题?

我可以拥有一个只有 get 的属性吗?

【问题讨论】:

  • 您将在 SetRatio 和 Voltage 中创建堆栈溢出异常。当 VS 加载您的控件时,它会执行此代码并且操作系统将关闭它。

标签: c# visual-studio-2015 crash


【解决方案1】:

可能有几个原因,但很可能是因为这会导致无限循环,从而导致 StackOverflow:

public int SetRatio
{
    set
    {
        if (value == 1) this.ratio_1.Checked = true;
        if (value == 2) this.ratio_34.Checked = true;
        if (value == 3) this.ratio_12.Checked = true;
        if (value == 4) this.ratio_14.Checked = true;
        SetRatio = value;
    }
}

最后一行 SetRatio 可能正在调用 SetRatio 属性设置器,这会导致代码再次从以下位置开始执行:

 if (value == 1) this.ratio_1.Checked = true;
 if (value == 2) this.ratio_34.Checked = true;
 if (value == 3) this.ratio_12.Checked = true;
 if (value == 4) this.ratio_14.Checked = true;
 SetRatio = value;

并且永远循环。 VS 和 .Net 不能很好地处理堆栈溢出和内存不足异常。

试试:

int setRatio;
public int SetRatio
{
    set
    {
        if (value == 1) this.ratio_1.Checked = true;
        if (value == 2) this.ratio_34.Checked = true;
        if (value == 3) this.ratio_12.Checked = true;
        if (value == 4) this.ratio_14.Checked = true;
        setRatio = value;
    }
}

如果这不起作用,请尝试更改您的构造函数,看看是否是导致问题的原因,因为带有抛出异常的构造函数的控件也会导致 VS 崩溃:

 public displayvoltage()
{
    InitializeComponent();
    //if (!this.ratio_1.Checked && !this.ratio_12.Checked && !this.ratio_34.Checked && !this.ratio_14.Checked)
    //    this.ratio_1.Checked = true;
}

【讨论】:

  • 构造函数导致了问题,即使我只是在构建解决方案,它也开始崩溃。谢谢。
猜你喜欢
  • 1970-01-01
  • 2014-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2019-07-06
相关资源
最近更新 更多