淺談c#開(kāi)發(fā)者應(yīng)該了解的15個(gè)特性
1. ObsoleteAttribute
ObsoleteAttribute 適用于除組件、模塊、參數(shù)和返回值以外的所有程序元素。將元素標(biāo)記為 obsolete,可以通知用戶該元素將在未來(lái)的版本中刪除。
IsError- 設(shè)置為 true,編譯器將在代碼中使用這個(gè)屬性時(shí),提示錯(cuò)誤。
public static class ObsoleteExample { // Mark OrderDetailTotal As Obsolete. [ObsoleteAttribute("This property (DepricatedOrderDetailTotal) is obsolete. Use InvoiceTotal instead.", false)] public static decimal OrderDetailTotal { get { return 12m; } } public static decimal InvoiceTotal { get { return 25m; } } // Mark CalculateOrderDetailTotal As Obsolete. [ObsoleteAttribute("This method is obsolete. Call CalculateInvoiceTotal instead.", true)] public static decimal CalculateOrderDetailTotal() { return 0m; } public static decimal CalculateInvoiceTotal() { return 1m; } }
如果我們?cè)诖a中使用上述類,則會(huì)顯示錯(cuò)誤和警告。
Console.WriteLine(ObsoleteExample.OrderDetailTotal); Console.WriteLine( ); Console.WriteLine(ObsoleteExample.CalculateOrderDetailTotal());
官方文檔-https://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx
2. 使用 DefaultValueAttribute 為 C# 自動(dòng)實(shí)現(xiàn)的屬性設(shè)置默認(rèn)值
DefaultValueAttribute 可以指定屬性的默認(rèn)值。你可以使用 DefaultValueAttribute 創(chuàng)建任意一個(gè)值。成員的默認(rèn)值通常是其初始值。
這個(gè)屬性不能用于使用特定的值自動(dòng)初始化對(duì)象成員。因此,開(kāi)發(fā)者必須在代碼中設(shè)置初始值。
public class DefaultValueAttributeTest { public DefaultValueAttributeTest() { // Use the DefaultValue property of each property to actually set it, via reflection. foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(this)) { DefaultValueAttribute attr = (DefaultValueAttribute)prop.Attributes [typeof(DefaultValueAttribute)]; if (attr != null) { prop.SetValue(this, attr.Value); } } } [DefaultValue(25)] public int Age { get; set; } [DefaultValue("Anton")] public string FirstName { get; set; } [DefaultValue("Angelov")] public string LastName { get; set; } public override string ToString() { return string.Format("{0} {1} is {2}.", this.FirstName, this.LastName, this.Age); } }
自動(dòng)實(shí)現(xiàn)的屬性通過(guò)反射在類的構(gòu)造函數(shù)中實(shí)現(xiàn)初始化。代碼遍歷類的所有屬性,并將它們?cè)O(shè)置為默認(rèn)值。
官方文檔-https://msdn.microsoft.com/zh-CN/library/system.componentmodel.defaultvalueattribute.aspx
3. DebuggerBrowsableAttribute
DebuggerBrowsableAttribute 用于確定是否需要以及如何實(shí)現(xiàn)在調(diào)試器變量窗口中顯示成員變量。
public static class DebuggerBrowsableTest { private static string squirrelFirstNameName; private static string squirrelLastNameName; // The following DebuggerBrowsableAttribute prevents the property following it // from appearing in the debug window for the class. [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static string SquirrelFirstNameName { get { return squirrelFirstNameName; } set { squirrelFirstNameName = value; } } [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public static string SquirrelLastNameName { get { return squirrelLastNameName; } set { squirrelLastNameName = value; } } }
官方文檔-https://msdn.microsoft.com/zh-CN/library/system.diagnostics.debuggerbrowsableattribute.aspx
4. ??運(yùn)算符
當(dāng)左操作數(shù)非空時(shí),??運(yùn)算符返回左邊的操作數(shù),否則返回右邊的操作數(shù)。??運(yùn)算符定義為,將可空類型分配給非空類型時(shí)要返回的默認(rèn)值。
int? x = null; int y = x ?? -1; Console.WriteLine("y now equals -1 because x was null => {0}", y); int i = DefaultValueOperatorTest.GetNullableInt() ?? default(int); Console.WriteLine("i equals now 0 because GetNullableInt() returned null => {0}", i); string s = DefaultValueOperatorTest.GetStringValue(); Console.WriteLine("Returns 'Unspecified' because s is null => {0}", s ?? "Unspecified");
官方文檔-https://msdn.microsoft.com/zh-cn/library/ms173224(v=vs.80).aspx
5. Curry和 Partial 方法
Curry- 在數(shù)學(xué)和計(jì)算機(jī)科學(xué)中,currying 是一種將函數(shù)的評(píng)估轉(zhuǎn)換為多個(gè)參數(shù)(或參數(shù)元組)的技術(shù),主要用于評(píng)估一系列函數(shù),每個(gè)函數(shù)都有一個(gè)參數(shù)。
為了通過(guò) C# 實(shí)現(xiàn),使用擴(kuò)展方法的功能。
public static class CurryMethodExtensions { public static Func<A, Func<B, Func<C, R>>> Curry<A, B, C, R>(this Func<A, B, C, R> f) { return a => b => c => f(a, b, c); } } Func<int, int, int, int> addNumbers = (x, y, z) => x + y + z; var f1 = addNumbers.Curry(); Func<int, Func<int, int>> f2 = f1(3); Func<int, int> f3 = f2(4); Console.WriteLine(f3(5));
不同方法返回的類型可以與var關(guān)鍵字進(jìn)行交換。
官方文檔-https://en.wikipedia.org/wiki/Currying
Partial- 在計(jì)算機(jī)科學(xué)中,Partial應(yīng)用程序(或 Partial功能應(yīng)用程序)是指將一些參數(shù)固定到一個(gè)函數(shù)的過(guò)程,從而產(chǎn)生另一個(gè)更小的函數(shù)。
public static class CurryMethodExtensions { public static Func<C, R> Partial<A, B, C, R>(this Func<A, B, C, R> f, A a, B b) { return c => f(a, b, c); } }
Partial擴(kuò)展方法的使用比 Curry更直接。
Func<int, int, int, int> sumNumbers = (x, y, z) => x + y + z; Func<int, int> f4 = sumNumbers.Partial(3, 4); Console.WriteLine(f4(5));
官方文檔-https://en.wikipedia.org/wiki/Partial_application
6. WeakReference
弱引用使得在收集器收集對(duì)象時(shí),仍允許應(yīng)用程序訪問(wèn)該對(duì)象。如果你需要這個(gè)對(duì)象,你仍然可以獲得一個(gè)強(qiáng)有力的引用,并阻止它被收集。
WeakReferenceTest hugeObject = new WeakReferenceTest(); hugeObject.SharkFirstName = "Sharky"; WeakReference w = new WeakReference(hugeObject); hugeObject = null; GC.Collect(); Console.WriteLine((w.Target as WeakReferenceTest).SharkFirstName);
如果垃圾收集器沒(méi)有明確被地調(diào)用,那么仍有很大的可能性弱引用會(huì)被分配。
官方文檔-https://msdn.microsoft.com/en-us/library/system.weakreference.aspx
7. Lazy<T>
使用延遲初始化,可推遲創(chuàng)建大型資源密集型對(duì)象或執(zhí)行資源密集型任務(wù)時(shí),在程序生命周期內(nèi)創(chuàng)建或執(zhí)行指定類的發(fā)生。
public abstract class ThreadSafeLazyBaseSingleton<T> where T : new() { private static readonly Lazy<T> lazy = new Lazy<T>(() => new T()); public static T Instance { get { return lazy.Value; } } }
官方文檔-https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
8. BigInteger
BigInteger 類型是一個(gè)不可變類型,它表示一個(gè)任意大的整數(shù),理論上它的值沒(méi)有上限或下限。這種類型與 .NET Framework 中的其他整型類型不同,這種類型具有自身 MinValue 和 MaxValue 屬性指示的范圍。
注意:因?yàn)?BigInteger 類型是不可變的,并且因?yàn)樗鼪](méi)有上限或下限,所以對(duì)于導(dǎo)致 BigInteger 值變得太大的任何操作,都會(huì)引發(fā) OutOfMemoryException。
string positiveString = "91389681247993671255432112000000"; string negativeString = "-90315837410896312071002088037140000"; BigInteger posBigInt = 0; BigInteger negBigInt = 0; posBigInt = BigInteger.Parse(positiveString); Console.WriteLine(posBigInt); negBigInt = BigInteger.Parse(negativeString); Console.WriteLine(negBigInt);
官方文檔-https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
9.沒(méi)有官方文檔的C#關(guān)鍵字 (__arglist / __reftype / __makeref / __refvalue)
一些 C# 關(guān)鍵字是沒(méi)有官方文檔的,沒(méi)有文檔的原因可能是這些關(guān)鍵字沒(méi)有經(jīng)過(guò)充分測(cè)試。但是,這些關(guān)鍵字已被 Visual Studio 編輯器著色并被識(shí)別為官方關(guān)鍵字。
你可以使用 __makeref 關(guān)鍵字在變量中創(chuàng)建一個(gè)類型化的引用,使用 __reftype 關(guān)鍵字提取由類型化引用表示的變量的原始類型,從 TypedReference 中使用 __refvalue 關(guān)鍵字獲取參數(shù)值,使用 __arglist 訪問(wèn)參數(shù)列表。
int i = 21; TypedReference tr = __makeref(i); Type t = __reftype(tr); Console.WriteLine(t.ToString()); int rv = __refvalue( tr,int); Console.WriteLine(rv); ArglistTest.DisplayNumbersOnConsole(__arglist(1, 2, 3, 5, 6));
在使用 __arglist 時(shí),需要 ArglistTest 類。
public static class ArglistTest { public static void DisplayNumbersOnConsole(__arglist) { ArgIterator ai = new ArgIterator(__arglist); while (ai.GetRemainingCount() > 0) { TypedReference tr = ai.GetNextArg(); Console.WriteLine(TypedReference.ToObject(tr)); } } }
參考-http://www.nullskull.com/articles/20030114.asp和http://community.bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx
10. Environment.NewLine
獲取當(dāng)前環(huán)境下的換行字符串。
Console.WriteLine("NewLine: {0} first line{0} second line{0} third line", Environment.NewLine);
官方文檔-https://msdn.microsoft.com/en-us/library/system.environment.newline(v=vs.110).aspx
11. ExceptionDispatchInfo
保留代碼中的某個(gè)被捕獲的異常。你可以使用 ExceptionDispatchInfo.Throw 方法,這個(gè)方法在 System.Runtime.ExceptionServicesnamespace 中。這個(gè)方法可用于引發(fā)異常并保留原始堆棧的調(diào)用過(guò)程。
ExceptionDispatchInfo possibleException = null; try { int.Parse("a"); } catch (FormatException ex) { possibleException = ExceptionDispatchInfo.Capture(ex); } if (possibleException != null) { possibleException.Throw(); }
被捕獲的異??梢栽诹硪粋€(gè)方法或另一個(gè)線程中再次拋出。
官方文檔-https://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo(v=vs.110).aspx
12. Environment.FailFast()
如果你想在不調(diào)用任何 finally 塊或終結(jié)器的情況下退出程序,可以使用 FailFast。
string s = Console.ReadLine(); try { int i = int.Parse(s); if (i == 42) Environment.FailFast("Special number entered"); } finally { Console.WriteLine("Program complete."); }
如果 i 等于 42,該 finally 塊將不會(huì)被執(zhí)行。
官方文檔-https://msdn.microsoft.com/zh-cn/library/ms131100(v=vs.110).aspx
13. Debug.Assert&Debug.WriteIf&Debug.Indent
Debug.Assert用于檢查條件,如果條件是 false,則輸出消息并顯示一個(gè)顯示調(diào)用堆棧的消息框。
Debug.Assert(1 == 0, "The numbers are not equal! Oh my god!");
如果斷言在調(diào)試模式下失敗,則顯示下面的警報(bào),其中包含指定的消息。
Debug.WriteIf- 如果判斷的結(jié)果是 true,則會(huì)將有關(guān)調(diào)試的信息寫(xiě)入 Listeners 收集中的跟蹤偵聽(tīng)器內(nèi)。
Debug.WriteLineIf(1 == 1, "This message is going to be displayed in the Debug output! =)");
Debug.Indent/Debug.Unindent– 使得 IndentLevel 逐一遞增。
Debug.WriteLine("What are ingredients to bake a cake?"); Debug.Indent(); Debug.WriteLine("1. 1 cup (2 sticks) butter, at room temperature."); Debug.WriteLine("2 cups sugar"); Debug.WriteLine("3 cups sifted self-rising flour"); Debug.WriteLine("4 eggs"); Debug.WriteLine("1 cup milk"); Debug.WriteLine("1 teaspoon pure vanilla extract"); Debug.Unindent(); Debug.WriteLine("End of list");
如果想在調(diào)試輸出窗口中顯示 cake的成分,可以使用上面的代碼。
官方文檔:Debug.Assert,Debug.WriteIf,Debug.Indent / Debug.Unindent
14. Parallel.For&Parallel.Foreach
Parallel.For- 執(zhí)行一個(gè)可并行運(yùn)行迭代的 for 循環(huán)。
int[] nums = Enumerable.Range(0, 1000000).ToArray(); long total = 0; // Use type parameter to make subtotal a long, not an int Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) => { subtotal += nums[j]; return subtotal; }, (x) => Interlocked.Add(ref total, x) ); Console.WriteLine("The total is {0:N0}", total);
Interlocked.Add方法添加兩個(gè)整數(shù),并用總和替換第一個(gè)整數(shù)。
Parallel.Foreach- 執(zhí)行可并行運(yùn)行迭代的 foreach 操作。
int[] nums = Enumerable.Range(0, 1000000).ToArray(); long total = 0; Parallel.ForEach<int, long>(nums, // source collection () => 0, // method to initialize the local variable (j, loop, subtotal) => // method invoked by the loop on each iteration { subtotal += j; //modify local variable return subtotal; // value to be passed to next iteration }, // Method to be executed when each partition has completed. // finalResult is the final value of subtotal for a particular partition. (finalResult) => Interlocked.Add(ref total, finalResult)); Console.WriteLine("The total from Parallel.ForEach is {0:N0}", total);
官方文檔:Parallel.For和Parallel.Foreach
15. IsInfinity
返回一個(gè)值,用于表示某一個(gè)數(shù)是否為負(fù)無(wú)窮或正無(wú)窮大。
Console.WriteLine("IsInfinity(3.0 / 0) == {0}.", Double.IsInfinity(3.0 / 0) ? "true" : "false");
官方文檔-https://msdn.microsoft.com/en-us/library/system.double.isinfinity(v=vs.110).aspx
以上就是淺談c#開(kāi)發(fā)者應(yīng)該了解的15個(gè)特性的詳細(xì)內(nèi)容,更多關(guān)于c#開(kāi)發(fā)者應(yīng)該了解的15個(gè)特性的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#線程 BeginInvoke和EndInvoke使用方法
本文開(kāi)始C#線程系列講座之一,即BeginInvoke和EndInvoke的使用方法,需要的朋友可以參考下2013-05-05C#中ListView控件實(shí)現(xiàn)窗體代碼
這篇文章主要介紹了C#中ListView控件實(shí)現(xiàn)窗體的核心代碼,非常不錯(cuò),具有參考借鑒價(jià)值,對(duì)c#listview相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2016-08-08講解C#面相對(duì)象編程中的類與對(duì)象的特性與概念
這篇文章主要介紹了C#面相對(duì)象編程中的類與對(duì)象的特性與概念,OOP面向?qū)ο笳Z(yǔ)言相對(duì)C語(yǔ)言這樣面相過(guò)程的語(yǔ)言來(lái)說(shuō)具有類和對(duì)象以及方法這樣的特性,需要的朋友可以參考下2016-01-01基于NET?Core?的Nuget包制作、發(fā)布和運(yùn)用流程解析(完整過(guò)程)
這篇文章主要介紹了基于NET?Core?的Nuget包制作、發(fā)布和運(yùn)用流程,本文通過(guò)圖文并茂的形式給大家介紹了Nuget包制作過(guò)程,感興趣的朋友跟隨小編一起看看吧2022-02-02Unity?UGUI的GraphicRaycaster射線投射組件介紹使用
這篇文章主要為大家介紹了Unity?UGUI的GraphicRaycaster射線投射組件介紹使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07c#簡(jiǎn)單工廠、工廠方法與抽象工廠的區(qū)別分析
看了網(wǎng)絡(luò)上很多關(guān)于設(shè)計(jì)模式的方法,有的模式看起來(lái)相似,但本質(zhì)還是區(qū)別很大的.像簡(jiǎn)單工廠,工廠方法和抽象工廠就有很明顯的區(qū)別.2013-03-03Unity打開(kāi)淘寶app并跳轉(zhuǎn)到商品頁(yè)面功能的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于如何利用Unity打開(kāi)淘寶app并跳轉(zhuǎn)到商品頁(yè)面功能的相關(guān)資料,這個(gè)功能目前在網(wǎng)上找不到相關(guān)的解決方法,所以自己寫(xiě)了出來(lái),需要的朋友可以參考下2021-07-07