学习学习在学习代码改变世界程序员

【C#学习笔记】C#中set和get用法

2015-05-20  本文已影响6537人  Jason_Yuan

目录###

1. c#中的域与属性
2. 为什么会出现set和get
3. 使用set和get的好处


1. c#中的域与属性

首先,先来谈一谈c#中的两个概念,域与属性。

1.1 域(field)

1.2 属性(property)


2. 为什么会出现set和get

面向对象的基本原则:
封装(Encapsulation)
多态(Polymorphism)
继承(Inheritance)

public class MyClass
{
    // this is a field.  It is private to your class and stores the actual data.
    private string _myField;

    // this is a property.  When you access it uses the underlying field, but only exposes
    // the contract that will not be affected by the underlying field
    public string MyField
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }
}

3. 使用set和get的好处

class Bank
    {
        private int money;//私有字段

        public int Money  //属性
        {
            get { return money;  }
            //增加限制,存钱不能为负数
            set
            {
                if (value >= 0) {
                    money = value;
                }
                else {
                    money = 0; 
                }
            }
        }
    }

4. 自动属性(Auto-Implemented Properties)

public class Student
{
    public string Name { get; set; }
}
public class Student
{
    private string name; // This is the so-called "backing field"
    public string Name // This is your property
    {
        get {return name;}
        set {name = value;}
    }
}

总结与参考文献

本文是笔者学习c#过程中的读书笔记,鞭策自己深入学习,也方便以后复习参考。内容会持续更新。更多内容可参见下面的参考文献。错误之处,还望指出,共同进步。

  1. C#域与属性
  2. C# 属性(Property)
  3. What is the { get; set; } syntax in C#?
  4. 浅析C# get set的简单用法
上一篇 下一篇

猜你喜欢

热点阅读