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. 属性访问器不应有过多影响性能操作,如访问数据库,保证其在使用时和使用变量有类似的性能
原文地址:https://www.cnblogs.com/haokaibo/p/2096524.html