• 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         }
  • 相关阅读:
    前端css常用class命名id命名
    javaScript获取url问号后面的参数
    ASP.NET MVC 基础知识整理(一)
    Java基础概念(二)
    Java基础概念(一)
    ionic隐藏头部导航栏
    ionic开发中页面跳转隐藏底部Ttab
    /Date(1354116249000)/ 这样的格式怎么转成时间格式 JS
    ionic ng-repeat 循环传值
    ionic页面跳转传值 ng-click
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/3038989.html
Copyright © 2020-2023  润新知