Why do we use .NET properties instead of plain old get/set functions?

前端 未结 15 1752
自闭症患者
自闭症患者 2020-12-25 15:06

I understand the many benefits of providing an interface to access the members of a class indirectly. My question is: isn\'t that already something you can accomplish in jus

15条回答
  •  -上瘾入骨i
    2020-12-25 15:28

    With get and set methods you have to decide to use them from the start and almost always write a lot of boilerplate code for every public property your classes expose.

    class Point
    {
        private int x, y;
    
        // Ew, pointless boilerplate!
        public int  getX()      { return x;   }
        public void setX(int x) { this.x = x; }
    
        public int  getY()      { return y;   }
        public void setY(int y) { this.y = y; }
    }
    
    // ...
    
    Point p = new Point();
    p.setX(5);
    p.setY(10);
    

    With properties you can eliminate the boilerplate getters and setters for the 90% of properties that have only trivial getters and setters. You can just have public variables exposed directly

    class Point
    {
        public int x, y;
    }
    
    Point p = new Point();
    p.x = 5;
    p.y = 10;
    

    Then later if you decide you want to add some behavior to your public variables you can switch them to properties with actual behavior in the get or set methods. The up side here is that users of your class are not affected at all. Nothing's changed; they don't have to switch from point.x = 5 to point.setX(5). Your public interface is stable, allowing you to use plain variables at first and switch to slower get/set methods later when you add some guarding/logging/whatever.

    class Point
    {
        public int x { get; set; }
    }
    
    // No change! 
    Point p = new Point();
    p.x = 5;
    p.y = 10;
    

    (Now strictly speaking, your syntactical interface hasn't changed, but your class's compiled interface has changed, so you do have to recompile all the code that uses your class if you switch from variables to properties. You can't get away with just recompiling your class and dropping that in place of the old class, if your class is part of a widely-used library, say. Your library's users would have to recompile their code against the new version of your library.)

提交回复
热议问题