繁体   English   中英

UserControl在C#中获取set属性

[英]UserControl get set Property in C#

我收到类似的错误

“在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;
        }
    }

您的设置程序是递归的,因为您有

this.MaxLength = value;

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

采用

this._vin = value;

代替

您的财产的设定者在这条线上叫自己:

 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中显示的“调用堆栈”窗口有助于查看哪些方法在无限循环中相互调用。 属性的设置器最终会在运行时成为名为set_MaxLength的方法。

this.MaxLength = value

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM