by
294 13
0
4
4,222
0
Top 1% !
Popular
Famous
Specified
Popularity: 2398th place
This snippet is Public
No tags for this snippet yet.
LanguageCSharp
LicenseMIT_X11
SourceGithub
SourceMyGists

immutable-atomic-value-types

http://www.tracefact.net/csharp-programming/immutable-atomic-value-types.aspx
1、当创建类型的目的是为了存储一组相关的数据,且数据量不是很大的时候,将它声明为Struct比Class会获得更高的效率;2、将类型声明为具有原子性和常量性,可以避免可能出现的数据不一致问题;3、通过在构造函数和Get访问器中,对对象的字段进行深度复制,可以避免在类型的外部修改类型内部数据的问题。: 
immutable-atomic-value-types.cs
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/21119/immutable-atomic-value-types?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
void Main() { string [] phones = { "18668866886", "18612341234" }; 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; } }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus