本文翻譯自:https://www.codeproject.com/Articles/1021335/Top-Underutilized-Features-of-NET
公司主營(yíng)業(yè)務(wù):成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)公司是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。成都創(chuàng)新互聯(lián)公司推出萬(wàn)年免費(fèi)做網(wǎng)站回饋大家。
轉(zhuǎn)載請(qǐng)注明出自:葡萄城官網(wǎng),葡萄城為開發(fā)者提供專業(yè)的開發(fā)工具、解決方案和服務(wù),賦能開發(fā)者。
本文列舉了 15 個(gè)值得了解的 C# 特性,旨在讓 .NET 開發(fā)人員更好的使用 C# 語(yǔ)言進(jìn)行開發(fā)工作。
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
DefaultValueAttribute 可以指定屬性的默認(rèn)值。你可以使用 DefaultValueAttribute 創(chuàng)建任意一個(gè)值。成員的默認(rèn)值通常是其初始值。
這個(gè)屬性不能用于使用特定的值自動(dòng)初始化對(duì)象成員。因此,開發(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)的屬性通過反射在類的構(gòu)造函數(shù)中實(shí)現(xiàn)初始化。代碼遍歷類的所有屬性,并將它們?cè)O(shè)置為默認(rèn)值。
官方文檔 - https://msdn.microsoft.com/zh-CN/library/system.componentmodel.defaultvalueattribute.aspx
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
當(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
Curry - 在數(shù)學(xué)和計(jì)算機(jī)科學(xué)中,currying 是一種將函數(shù)的評(píng)估轉(zhuǎn)換為多個(gè)參數(shù)(或參數(shù)元組)的技術(shù),主要用于評(píng)估一系列函數(shù),每個(gè)函數(shù)都有一個(gè)參數(shù)。
為了通過 C# 實(shí)現(xiàn),使用擴(kuò)展方法的功能。

Func<A, Func<B, Func<C, R>>> Curry<A, B, C, R>( Func<A, B, C, R> a => b => c =><, , , > addNumbers = (x, y, z) => x + y + f1 =<, Func<, >> f2 = f1(<, > f3 = f2());

不同方法返回的類型可以與 var 關(guān)鍵字進(jìn)行交換。
官方文檔 - https://en.wikipedia.org/wiki/Currying#/Contrast_with_partial_function_application
Partial - 在計(jì)算機(jī)科學(xué)中,Partial 應(yīng)用程序(或 Partial 功能應(yīng)用程序)是指將一些參數(shù)固定到一個(gè)函數(shù)的過程,從而產(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
弱引用使得在收集器收集對(duì)象時(shí),仍允許應(yīng)用程序訪問該對(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);

如果垃圾收集器沒有明確被地調(diào)用,那么仍有很大的可能性弱引用會(huì)被分配。
官方文檔 - https://msdn.microsoft.com/en-us/library/system.weakreference.aspx
使用延遲初始化,可推遲創(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
BigInteger 類型是一個(gè)不可變類型,它表示一個(gè)任意大的整數(shù),理論上它的值沒有上限或下限。這種類型與 .NET Framework 中的其他整型類型不同,這種類型具有自身 MinValue 和 MaxValue 屬性指示的范圍。
注意:因?yàn)?BigInteger 類型是不可變的,并且因?yàn)樗鼪]有上限或下限,所以對(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
一些 C# 關(guān)鍵字是沒有官方文檔的,沒有文檔的原因可能是這些關(guān)鍵字沒有經(jīng)過充分測(cè)試。但是,這些關(guān)鍵字已被 Visual Studio 編輯器著色并被識(shí)別為官方關(guān)鍵字。
你可以使用 __makeref 關(guān)鍵字在變量中創(chuàng)建一個(gè)類型化的引用,使用 __reftype 關(guān)鍵字提取由類型化引用表示的變量的原始類型,從 TypedReference 中使用 __refvalue 關(guān)鍵字獲取參數(shù)值,使用 __arglist 訪問參數(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
獲取當(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
保留代碼中的某個(gè)被捕獲的異常。你可以使用 ExceptionDispatchInfo.Throw 方法,這個(gè)方法在 System.Runtime.ExceptionServices namespace 中。這個(gè)方法可用于引發(fā)異常并保留原始堆棧的調(diào)用過程。

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
如果你想在不調(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
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)試的信息寫入 Listeners 收集中的跟蹤偵聽器內(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
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 intParallel.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
返回一個(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
相關(guān)閱讀:
是什么優(yōu)化讓 .NET Core 性能飆升?
C#開發(fā)人員應(yīng)該知道的13件事情
是什么讓C#成為最值得學(xué)習(xí)的編程語(yǔ)言
關(guān)于葡萄城:
賦能開發(fā)者!葡萄城公司成立于 1980 年,是全球領(lǐng)先的集開發(fā)工具、商業(yè)智能解決方案、管理系統(tǒng)設(shè)計(jì)工具于一身的軟件和服務(wù)提供商。西安葡萄城是其在中國(guó)的分支機(jī)構(gòu),面向全球市場(chǎng)提供軟件研發(fā)服務(wù),并為中國(guó)企業(yè)的信息化提供國(guó)際先進(jìn)的開發(fā)工具、軟件和研發(fā)咨詢服務(wù)。葡萄城的控件和軟件產(chǎn)品在國(guó)內(nèi)外屢獲殊榮,在全球被數(shù)十萬(wàn)家企業(yè)、學(xué)校和政府機(jī)構(gòu)廣泛應(yīng)用。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
文章題目:值得.NET開發(fā)者了解的15個(gè)特性-創(chuàng)新互聯(lián)
本文路徑:http://chinadenli.net/article20/diihco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、關(guān)鍵詞優(yōu)化、網(wǎng)站策劃、定制網(wǎng)站、Google、外貿(mào)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容