理解为什么我在get方法中遇到递归错误

Bre*_*t0r -3 c# properties unity-game-engine

我目前正在学习属性并遇到了一些问题.当我在get方法中返回我的属性时,我收到一个递归错误.

这是因为每当我返回属性时它会激活get方法,它返回属性,激活get方法等?

这是我的代码:

using UnityEngine;

struct Enemy
{
    public int Bonus;
    private int gold; 

    public int Gold
    {
        get
        {
            return Gold + Bonus;  
        }                       
        set                 
        {
            gold = value; 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ips*_*aur 5

原因-

Gold在其getter 中使用该属性本身,该getter一次又一次地递归调用其getter.

解-

使用变量代替 -

public int Gold
{
    get
    {
        return gold + Bonus;  
    }    
    set                
    {
        gold = value; 
    }
}
Run Code Online (Sandbox Code Playgroud)