为什么此属性会导致StackOverFlow异常?

时间:2015-07-29 22:48:49

标签: c# properties get set prop

我稍微研究了这个错误,当我不断地调用setter时我似乎在递归,但我真的无法分辨出我做错了什么。我知道它可能也很简单。

 namespace PracticeCSharp
 {
class Program
{


    static void Main(string[] args)
    {
        Player test = new Player();
        test.Score = 5;
        Console.ReadLine();
    }

}
class Player
{
    public int Score
    {
        get
        {
            return Score;
        }
        set
        {
            Score = value;
        }
    }
}

}

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

因为Score属性会自行递归。

你的意思是这样做吗?

namespace PracticeCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Player test = new Player();
            test.Score = 5;
            Console.ReadLine();
        }

    }
    class Player
    {
        private int score;
        public int Score
        {
            get
            {
                return score;
            }
            set
            {
                score = value;
            }
        }
    }
}

<强>更新

或者你可以这样做:

namespace PracticeCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Player test = new Player();
            test.Score = 5;
            Console.ReadLine();
        }

    }
    class Player
    {
        public int Score { get; set; }
    }
}

答案 1 :(得分:1)

你必须声明得分变量

 namespace PracticeCSharp
 {    
    class Program
    {


        static void Main(string[] args)
        {
            Player test = new Player();
            test.Score = 5;
            Console.ReadLine();
        }

    }
    class Player
    {
        private int _score;
        public int Score
        {
            get
            {
                return _score;
            }
            set
            {
                _score = value;
            }
        }
    }
}