zoukankan      html  css  js  c++  java
  • Property总结

    Property一般用来给field赋值:

    View Code
    1 private string _name
    2 public string Name
    3 {
    4     get{return _name;}
    5     set{_name = value;}
    6 }

    可以给Field赋值的不只是property,也可以是constractor或者一个方法,但是如果我们想要向外暴露这个filed我们才需要写property

    View Code
     1 class Person
     2 {
     3     private string _name 
     4     public Person(string name)
     5     {
     6         _name = name;
     7     }
     8 }
     9 
    10 
    11 //或者
    12 
    13 class Person
    14 {
    15     private string _name 
    16     public void Person(string name)
    17     {
    18         _name = name;
    19     }
    20 }

    我们可以用Setter做更多事

    View Code
     1 private int _dividend;
     2         public int Dividend
     3         {
     4             get { return _dividend; }
     5             set
     6             {
     7                 if (value == 0)
     8                 {
     9                     throw new ArgumentException("Can not set dividend to 0!");
    10                 }
    11             }
    12         }

    就算只有一个数据传入口,我们也建议用property,代替public的field

    public string Name { get; set;}

    一般只有property,event,methord是puublic的其他结构都做private

    有的时候我们需要set bunch piece of propertys as unit,我们应该用一个方法去set property together

    View Code
     1 public string Name { get; private set; }
     2         public string Address { get; private set; }
     3         public int ZipCode { get; private set; }
     4         public string State { get; private set; }
     5 
     6         public void SetName(string name)
     7         {
     8             Name = name;
     9         }
    10         public void Move(string address, int zipCode, string state)
    11         {
    12             Address = address;
    13             ZipCode = zipCode;
    14             State = state;
    15         }
  • 相关阅读:
    C++细节3
    C++细节2
    C++细节1
    连通域标记方法
    dll动态链接库入门2
    UnixShell编程(第三版)
    Xcode 快捷键
    mysql在linux上的一点操作
    mysql 语句
    开机自动启动
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/3038989.html
Copyright © 2011-2022 走看看