Skip to content

Instantly share code, notes, and snippets.

@yicone
Created May 25, 2013 10:36
Show Gist options
  • Save yicone/5648640 to your computer and use it in GitHub Desktop.
Save yicone/5648640 to your computer and use it in GitHub Desktop.
http://www.tracefact.net/csharp-programming/immutable-atomic-value-types.aspx 1、当创建类型的目的是为了存储一组相关的数据,且数据量不是很大的时候,将它声明为Struct比Class会获得更高的效率;2、将类型声明为具有原子性和常量性,可以避免可能出现的数据不一致问题;3、通过在构造函数和Get访问器中,对对象的字段进行深度复制,可以避免在类型的外部修改类型内部数据的问题。
void Main()
{
string [] phones = { "18616386880", "18621168732" };
Foo foo = new Foo(phones);
Console.WriteLine(foo.Phones[0]);
phones[0] = "xxx";
Console.WriteLine(foo.Phones[0]);
foo.Phones[0] = "xxx";
Console.WriteLine(foo.Phones[0]);
}
// Define other methods and classes here
public class Foo
{
private readonly string[] _phones;
public string[] Phones { get{
var copy = new string[_phones.Length];
_phones.CopyTo(copy, 0);
return copy;
}}
public Foo(string[] phones)
{
var copy = new string[phones.Length];
phones.CopyTo(copy, 0);
_phones = copy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment