溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

值得 .NET 開發(fā)者了解的15個(gè)特性

發(fā)布時(shí)間:2020-05-15 05:08:10 來源:網(wǎng)絡(luò) 閱讀:373 作者:powertoolsteam 欄目:編程語言

本文翻譯自:https://www.codeproject.com/Articles/1021335/Top-Underutilized-Features-of-NET

轉(zhuǎn)載請注明出自:葡萄城官網(wǎng),葡萄城為開發(fā)者提供專業(yè)的開發(fā)工具、解決方案和服務(wù),賦能開發(fā)者。

 

本文列舉了 15 個(gè)值得了解的 C# 特性,旨在讓 .NET 開發(fā)人員更好的使用 C# 語言進(jìn)行開發(fā)工作。

1. ObsoleteAttribute

ObsoleteAttribute 適用于除組件、模塊、參數(shù)和返回值以外的所有程序元素。將元素標(biāo)記為 obsolete,可以通知用戶該元素將在未來的版本中刪除。
IsError - 設(shè)置為 true,編譯器將在代碼中使用這個(gè)屬性時(shí),提示錯(cuò)誤。

值得 .NET 開發(fā)者了解的15個(gè)特性

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;
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

如果我們在代碼中使用上述類,則會(huì)顯示錯(cuò)誤和警告。

Console.WriteLine(ObsoleteExample.OrderDetailTotal);
Console.WriteLine( );
Console.WriteLine(ObsoleteExample.CalculateOrderDetailTotal());

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔 - 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)初始化對象成員。因此,開發(fā)者必須在代碼中設(shè)置初始值。

值得 .NET 開發(fā)者了解的15個(gè)特性

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);
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

自動(dòng)實(shí)現(xiàn)的屬性通過反射在類的構(gòu)造函數(shù)中實(shí)現(xiàn)初始化。代碼遍歷類的所有屬性,并將它們設(shè)置為默認(rèn)值。

官方文檔 - https://msdn.microsoft.com/zh-CN/library/system.componentmodel.defaultvalueattribute.aspx

 

3. DebuggerBrowsableAttribute

DebuggerBrowsableAttribute 用于確定是否需要以及如何實(shí)現(xiàn)在調(diào)試器變量窗口中顯示成員變量。

值得 .NET 開發(fā)者了解的15個(gè)特性

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;
        }
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔 - 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)值。

值得 .NET 開發(fā)者了解的15個(gè)特性

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");

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔 - https://msdn.microsoft.com/zh-cn/library/ms173224(v=vs.80).aspx

 

5. Curry 和 Partial 方法

Curry - 在數(shù)學(xué)和計(jì)算機(jī)科學(xué)中,currying 是一種將函數(shù)的評估轉(zhuǎn)換為多個(gè)參數(shù)(或參數(shù)元組)的技術(shù),主要用于評估一系列函數(shù),每個(gè)函數(shù)都有一個(gè)參數(shù)。

為了通過 C# 實(shí)現(xiàn),使用擴(kuò)展方法的功能。

值得 .NET 開發(fā)者了解的15個(gè)特性

    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());

值得 .NET 開發(fā)者了解的15個(gè)特性

不同方法返回的類型可以與 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ù)。

值得 .NET 開發(fā)者了解的15個(gè)特性

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);
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

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

弱引用使得在收集器收集對象時(shí),仍允許應(yīng)用程序訪問該對象。如果你需要這個(gè)對象,你仍然可以獲得一個(gè)強(qiáng)有力的引用,并阻止它被收集。

值得 .NET 開發(fā)者了解的15個(gè)特性

WeakReferenceTest hugeObject = new WeakReferenceTest();
hugeObject.SharkFirstName = "Sharky";
WeakReference w = new WeakReference(hugeObject);
hugeObject = null;
GC.Collect();
Console.WriteLine((w.Target as WeakReferenceTest).SharkFirstName);

值得 .NET 開發(fā)者了解的15個(gè)特性

如果垃圾收集器沒有明確被地調(diào)用,那么仍有很大的可能性弱引用會(huì)被分配。

官方文檔 - https://msdn.microsoft.com/en-us/library/system.weakreference.aspx

 

7. Lazy<T>

使用延遲初始化,可推遲創(chuàng)建大型資源密集型對象或執(zhí)行資源密集型任務(wù)時(shí),在程序生命周期內(nèi)創(chuàng)建或執(zhí)行指定類的發(fā)生。

值得 .NET 開發(fā)者了解的15個(gè)特性

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;
        }
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔 - https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx

 

8. BigInteger

BigInteger 類型是一個(gè)不可變類型,它表示一個(gè)任意大的整數(shù),理論上它的值沒有上限或下限。這種類型與 .NET Framework 中的其他整型類型不同,這種類型具有自身 MinValue 和 MaxValue 屬性指示的范圍。

注意:因?yàn)?BigInteger 類型是不可變的,并且因?yàn)樗鼪]有上限或下限,所以對于導(dǎo)致 BigInteger 值變得太大的任何操作,都會(huì)引發(fā) OutOfMemoryException。

值得 .NET 開發(fā)者了解的15個(gè)特性

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);

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔 - https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

 

9.沒有官方文檔的C#關(guān)鍵字 (__arglist / __reftype / __makeref / __refvalue)

一些 C# 關(guān)鍵字是沒有官方文檔的,沒有文檔的原因可能是這些關(guān)鍵字沒有經(jīng)過充分測試。但是,這些關(guān)鍵字已被 Visual Studio 編輯器著色并被識(shí)別為官方關(guān)鍵字。

你可以使用 __makeref 關(guān)鍵字在變量中創(chuàng)建一個(gè)類型化的引用,使用 __reftype 關(guān)鍵字提取由類型化引用表示的變量的原始類型,從 TypedReference 中使用 __refvalue 關(guān)鍵字獲取參數(shù)值,使用 __arglist 訪問參數(shù)列表。

值得 .NET 開發(fā)者了解的15個(gè)特性

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));

值得 .NET 開發(fā)者了解的15個(gè)特性

在使用 __arglist 時(shí),需要 ArglistTest 類。

值得 .NET 開發(fā)者了解的15個(gè)特性

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));
        }
    }
}

值得 .NET 開發(fā)者了解的15個(gè)特性

參考 - 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.ExceptionServices namespace 中。這個(gè)方法可用于引發(fā)異常并保留原始堆棧的調(diào)用過程。

值得 .NET 開發(fā)者了解的15個(gè)特性

ExceptionDispatchInfo possibleException = null;try{    int.Parse("a");
}catch (FormatException ex)
{
    possibleException = ExceptionDispatchInfo.Capture(ex);
}if (possibleException != null)
{
    possibleException.Throw();
}

值得 .NET 開發(fā)者了解的15個(gè)特性

被捕獲的異??梢栽诹硪粋€(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。


值得 .NET 開發(fā)者了解的15個(gè)特性

string s = Console.ReadLine();try{    int i = int.Parse(s);    if (i == 42) Environment.FailFast("Special number entered");
}finally{
    Console.WriteLine("Program complete.");
}

值得 .NET 開發(fā)者了解的15個(gè)特性

如果 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),其中包含指定的消息。

值得 .NET 開發(fā)者了解的15個(gè)特性

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 逐一遞增。

值得 .NET 開發(fā)者了解的15個(gè)特性

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");

值得 .NET 開發(fā)者了解的15個(gè)特性

如果想在調(diào)試輸出窗口中顯示 cake 的成分,可以使用上面的代碼。

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔:Debug.Assert,Debug.WriteIf,Debug.Indent / Debug.Unindent

 

14. Parallel.For&Parallel.Foreach

Parallel.For - 執(zhí)行一個(gè)可并行運(yùn)行迭代的 for 循環(huán)。

值得 .NET 開發(fā)者了解的15個(gè)特性

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);

值得 .NET 開發(fā)者了解的15個(gè)特性

Interlocked.Add 方法添加兩個(gè)整數(shù),并用總和替換第一個(gè)整數(shù)。

Parallel.Foreach - 執(zhí)行可并行運(yùn)行迭代的 foreach 操作。

值得 .NET 開發(fā)者了解的15個(gè)特性

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);

值得 .NET 開發(fā)者了解的15個(gè)特性

官方文檔:Parallel.For 和 Parallel.Foreach

 

15. IsInfinity

返回一個(gè)值,用于表示某一個(gè)數(shù)是否為負(fù)無窮或正無窮大。

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í)的編程語言

關(guān)于葡萄城:

賦能開發(fā)者!葡萄城公司成立于 1980 年,是全球領(lǐng)先的集開發(fā)工具、商業(yè)智能解決方案、管理系統(tǒng)設(shè)計(jì)工具于一身的軟件和服務(wù)提供商。西安葡萄城是其在中國的分支機(jī)構(gòu),面向全球市場提供軟件研發(fā)服務(wù),并為中國企業(yè)的信息化提供國際先進(jìn)的開發(fā)工具、軟件和研發(fā)咨詢服務(wù)。葡萄城的控件和軟件產(chǎn)品在國內(nèi)外屢獲殊榮,在全球被數(shù)十萬家企業(yè)、學(xué)校和政府機(jī)構(gòu)廣泛應(yīng)用。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI