getter and setter for class in class c#

前端 未结 5 1821
攒了一身酷
攒了一身酷 2021-02-19 01:48

Assuming we have a class InnerClass with attributes and getter/setter. We also have a class OuterClass containing the InnerClass.

e.g.

class InnerClass
{         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 02:31

    The most elegant way of doing this is to use implicit getters and setters:

    class InnerClass
    {
      public int a{ get; set; }
      public int b{ get; set; }
    }
    
    class OuterClass
    {
      public InnerClass innerClass{ get; set; }
    }
    

    This is implicitly the same as:

    class InnerClass
    {
        private int _a;
        public int a
        {
            get
            {
                return _a;
            }
            set
            {
                _a = value;
            }
        }
    
        private int _b;
        public int b
        {
            get
            {
                return _b;
            }
            set
            {
                _b = value;
            }
        }
    }
    
    class OuterClass
    {
        private InnerClass _innerClass;
        public InnerClass innerClass
        {
            get
            {
                return _innerClass;
            }
            set
            {
                _innerClass = value;
            }
        }
    }
    

    These two definitions are implicitly the same - minus quite a few keystrokes. In the first example, the compiler will implement the necessary private fields behind the scenes so you don't have to. The second, however gives you more control of what is going on.

提交回复
热议问题