I am getting into infinite loop in property setter

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


        
相关标签:
4条回答
  • 2020-12-06 07:44

    There's nothing particularly string-like about session state items.

    Why wouldn't you just follow the KISS principle and do something like

    public int Position
    {
      get { return (int) ( Session["Position"] ?? 5 ) ; }
      set { Session["Position"] = value ;               }
    }
    

    or (depending on your actual requirements/specs:

    public int Position
    {
      get { return Session["Pointer"] as int? ?? position ?? 5 ; }
      set { position = value ; }
    }
    private int? position ; // backing store
    
    0 讨论(0)
  • 2020-12-06 07:57

    Use a member variable or perhaps store it in the session.

    private int _position;
    public int Position
    {
        get
        {
            if (Session["Position"] != null)
            {
                _position= Convert.ToInt32(Session["Position"]);
            }
            else
            {
                _position= 5;
            }
            return _position;
        }
        set
        {
            _position = value;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 08:02

    The error is because in your set {} you are invoking the same setter recursively.

    Correct code would be

    private int _position;
    public int Position
    {
        get
        {
            if (Session["Position"] != null)
            {
                this._position = Convert.ToInt32(Session["Position"]);
            }
            else
            {
                this._position = 5;
            }
            return this._position;
        }
        set
        {
            this._position = value;
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题