简体   繁体   English

UserControl在C#中获取set属性

[英]UserControl get set Property in C#

I am getting an error like 我收到类似的错误

"An unhandled exception of type 'System.StackOverflowException' occurred in ciscontrols.dll". “在ciscontrols.dll中发生了'System.StackOverflowException'类型的未处理的异常”。

My code is given below 我的代码如下

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

i am creating a new property for decimal places 我正在为小数位创建一个新属性

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

Your setter is recursive because you have 您的设置程序是递归的,因为您有

this.MaxLength = value;

Within your setter. 在你的二传手中。 This will result in an infinite loop, and eventually, a StackOverflowException . 这将导致无限循环,并最终导致StackOverflowException

Use 采用

this._vin = value;

Instead 代替

your property's setter is calling itself on this line: 您的财产的设定者在这条线上叫自己:

 this.MaxLength = value;

Change it to: 更改为:

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

For this particular exception, the Call Stack window displayed in Visual Studio while debugging is helpful in seeing which methods are calling each other in an infinite loop. 对于此特定异常,调试时在Visual Studio中显示的“调用堆栈”窗口有助于查看哪些方法在无限循环中相互调用。 The setter of a property eventually becomes a method called set_MaxLength in the run-time. 属性的设置器最终会在运行时成为名为set_MaxLength的方法。

this.MaxLength = value

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

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

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