简体   繁体   English

C#getter setter默认值

[英]C# getter setter default value

How do you set default value for setter getter? 如何设置setter吸气剂的默认值? I want to do some operations while setting the setter. 我想在设置设置器时进行一些操作。

public bool spin {
    get { return this.spin; }
    set {
        if (value == false) this.spinBack = true;
        this.spin = value;
    }
}
private bool spinBack;

I tried this on Unity3D and got this error when trying to do so. 我在Unity3D上尝试了此操作,并在尝试执行此操作时收到此错误。

StackOverflowException: The requested operation caused a stack overflow. StackOverflowException:请求的操作导致堆栈溢出。

I tried just setting the getter and leave getter as default like so 我尝试只设置吸气剂并将吸气剂保留为默认值

public bool spin {
    get;
    set {
        if (value == false) this.spinBack = true;
        this.spin = value;
    }
}
private bool spinBack;

but I get this error 但是我得到这个错误

'spin.get' must have a body because it is not marked abstract, extern, or partial 'spin.get'必须具有主体,因为它没有标记为抽象,外部或局部

The StackOverflowException is due to your this.spin = value; StackOverflowException是由于您的this.spin = value; line which is recursively setting spin . 递归设置spin

Use a backing field instead: 请使用后备字段:

public bool Spin 
{
    get { return _spin; }
    set {
        if (value == false) this.spinBack = true;
        _spin = value;
    }
}

private bool _spin;
private bool spinBack;

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

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