I am getting into infinite loop in property setter

前端 未结 4 653
盖世英雄少女心
盖世英雄少女心 2020-12-06 06:57
public int Position
{
    get
    {
        if (Session[\"Position\"] != null)
        {
            Position = Convert.ToInt32(Session[\"Position\"]);
        }
            


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-06 08:03

    An auto-implemented property property consists of a getter, a setter and a backing field. If you write the code yourself, a field might not be necessary.

    Your getter invokes setter, and the setter invokes setter; that would be infinite recursion. You might need a field for storing Position.

    However, if we change it with storing to a field, and the setter in fact doesn't effect. So, the code could be changed to:

    public int Position {
        set {
        }
    
        get {
            int x;
            return (x=Convert.ToInt32(Session["Position"]))>0?x:5;
        }
    }
    

    You don't need to check for null, Convert.ToInt32(null) is zero.

提交回复
热议问题