【问题标题】:UserControl get set Property in C#UserControl 在 C# 中获取设置属性
【发布时间】:2013-03-08 03:48:29
【问题描述】:

我收到类似的错误

“在 ciscontrols.dll 中发生了“System.StackOverflowException”类型的未处理异常”。

我的代码如下

    private int _vin;

    public int MaxLength
    {
        get { return _vin; }

        set //Here your answer solve the promblem
        {
            txtLocl.MaxLength = value;
            if (value < 2)
            {
                throw new ArgumentOutOfRangeException("MaxLength","MaxLength MinValue should be 2.");
            }
            else this._vin = value;
        }
    }

我正在为小数位创建一个新属性

private int Dval;
    public int DecPlaces
    {
        get { return Dval; }
        set// here it showing the same error
        {
            DecPlaces = value; // MaxLength is a preDefined Property but  DecPlaces created by me.
            if (value < 2)
            {
                throw new ArgumentOutOfRangeException("decplaces", "decimal places minimum value should be 2.");
            }
            else this.Dval = value;
        }
    }

【问题讨论】:

    标签: c# winforms user-controls textbox get


    【解决方案1】:

    你的属性的 setter 在这一行调用自己:

     this.MaxLength = value;
    

    改成:

    set //Here i am getting Error
    {
        txtLocl.MaxLength = value;
        if (value < 2)
        {
            throw new ArgumentOutOfRangeException("MaxLength","MaxLength MinValue should be 2.");
        }
        else this._vin = value;
    }
    

    对于此特定异常,调试时 Visual Studio 中显示的调用堆栈窗口有助于查看哪些方法在无限循环中相互调用。属性的 setter 最终会在运行时成为一个名为 set_MaxLength 的方法。

    【讨论】:

    • 谢谢我明白先生...,
    • 当设置器说 DecPlaces =value 时,您再次在新代码中创建无限循环。这会导致 setter 再次调用自身。将其更改为 Dval =value 或更改它以设置控件的值,就像您在第一个示例中所做的那样。设置者应该设置字段而不是自己。
    【解决方案2】:

    你的 setter 是递归的,因为你有

    this.MaxLength = value;
    

    在您的二传手内。这将导致无限循环,并最终导致StackOverflowException

    使用

    this._vin = value;
    

    相反

    【讨论】:

      【解决方案3】:
      this.MaxLength = value
      

      这一行触发了一个无限循环,因为它调用了您已经在其中的set 访问器。您的意思是设置一个支持变量的值吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 2012-03-08
        相关资源
        最近更新 更多