zoukankan      html  css  js  c++  java
  • Effective C# 学习笔记(一) 用属性替代公有变量

    好久没写东西了,现在找到本好书,写下读书笔记,在帮助自己记忆的同时,与大家分享。 :)

    意义: 可以统一管理公有变量的set get行为

    作用:

    1. 对对象属性添加多线程支持

    public class Customer

    {

    private object syncHandle = new object();

    private string name;

    public string Name

    {

    get

    {

    lock (syncHandle)

    return name;

    }

    set

    {

    if (string.IsNullOrEmpty(value))

    throw new ArgumentException(

    "Name cannot be blank",

    "Name");

    lock (syncHandle)

    name = value;

    }

    }

    // More Elided.

    }

    1. 将属性设置为 虚属性

    public class Customer

    {

    public virtual string Nam

    {

    get;

    set;

    }

    }

    1. 在接口中定义属性

    public interface INameValuePair<T>

    {

    string Name

    {

    get;

    }

    T Value

    {

    get;

    set;

    }

    }

    1. 可以分别定义属性的get set 的可访问性

    public class Customer

    {

    public virtual string Name

    {

    get;

    protected set;

    }

    // remaining implementation omitte

    }

    1. 调用索引器数值参数索引可以用来做data binding

    public int this[int index]

    {

    get { return theValues[index]; }

    set { theValues[index] = value; }

    }

    // Accessing an indexer:

    int val = someObject[i];

     

    非数值类型参数可以用作maps Dictionaries

    public Address this[string name]

    {

    get { return adressValues[name]; }

    set { adressValues[name] = value; }

    }

     

    多维索引

    public int this[int x, int y]

    {

    get { return ComputeValue(x, y); }

    }

    public int this[int x, string name]

    {

    get { return ComputeValue(x, name);

    }

    属性与变量比较

    1. 属性的改变只会影响到类定义的部分,而公有变量重定义为属性后会影响到所有使用该变量的地方
    2. 属性访问器不应有过多影响性能操作,如访问数据库,保证其在使用时和使用变量有类似的性能
  • 相关阅读:
    kubernetes 在pod内无法ping通servicename和ClusterIP的解决方法
    最小安装的服务器怎么使用nm-connection-editor
    CentOS 系统升级系统内核版本
    kubernetes学习资料
    Docker学习笔记--(超详细)
    Cheat Engine 注入++: (密码=31337157)
    Jupyter-Notebook开机自启动
    kali远程桌面-krdp
    Win10 快捷方式小箭头及小盾牌如何替换
    NumPy学习心得(二)
  • 原文地址:https://www.cnblogs.com/haokaibo/p/2096524.html
Copyright © 2011-2022 走看看