這15個特性,身爲.NET開發者的你全部都瞭解嗎?

轉載請註明出自:葡萄城官網,葡萄城爲開發者提供專業的開發工具、解決方案和服務,賦能開發者。


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

1. ObsoleteAttribute

ObsoleteAttribute 適用於除組件、模塊、參數和返回值以外的所有程序元素。將元素標記爲 obsolete,可以通知用戶該元素將在未來的版本中刪除。
IsError - 設置爲 true,編譯器將在代碼中使用這個屬性時,提示錯誤。

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

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

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

圖片描述

官方文檔 - https://msdn.microsoft.com/en...

2. 使用 DefaultValueAttribute 爲 C# 自動實現的屬性設置默認值
DefaultValueAttribute 可以指定屬性的默認值。你可以使用 DefaultValueAttribute 創建任意一個值。成員的默認值通常是其初始值。

這個屬性不能用於使用特定的值自動初始化對象成員。因此,開發者必須在代碼中設置初始值。

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

自動實現的屬性通過反射在類的構造函數中實現初始化。代碼遍歷類的所有屬性,並將它們設置爲默認值。

官方文檔 - https://msdn.microsoft.com/zh...

3. DebuggerBrowsableAttribute
DebuggerBrowsableAttribute 用於確定是否需要以及如何實現在調試器變量窗口中顯示成員變量。

    
    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...

4. ?? 運算符
當左操作數非空時,?? 運算符返回左邊的操作數,否則返回右邊的操作數。?? 運算符定義爲,將可空類型分配給非空類型時要返回的默認值。

    
    
    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...

5. Curry 和 Partial 方法
Curry - 在數學和計算機科學中,currying 是一種將函數的​​評估轉換爲多個參數(或參數元組)的技術,主要用於評估一系列函數,每個函數都有一個參數。

爲了通過 C# 實現,使用擴展方法的功能。

    
    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 關鍵字進行交換。

官方文檔 - https://en.wikipedia.org/wiki...

Partial - 在計算機科學中,Partial 應用程序(或 Partial 功能應用程序)是指將一些參數固定到一個函數的過程,從而產生另一個更小的函數。

    
    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 擴展方法的使用比 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...

6. WeakReference
弱引用使得在收集器收集對象時,仍允許應用程序訪問該對象。如果你需要這個對象,你仍然可以獲得一個強有力的引用,並阻止它被收集。

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

如果垃圾收集器沒有明確被地調用,那麼仍有很大的可能性弱引用會被分配。

官方文檔 - https://msdn.microsoft.com/en...

7. Lazy<T>
使用延遲初始化,可推遲創建大型資源密集型對象或執行資源密集型任務時,在程序生命週期內創建或執行指定類的發生。

    
    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...

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

注意:因爲 BigInteger 類型是不可變的,並且因爲它沒有上限或下限,所以對於導致 BigInteger 值變得太大的任何操作,都會引發 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...

9.沒有官方文檔的C#關鍵字 (__arglist / __reftype / __makeref / __refvalue)
一些 C# 關鍵字是沒有官方文檔的,沒有文檔的原因可能是這些關鍵字沒有經過充分測試。但是,這些關鍵字已被 Visual Studio 編輯器着色並被識別爲官方關鍵字。

你可以使用 __makeref 關鍵字在變量中創建一個類型化的引用,使用 __reftype 關鍵字提取由類型化引用表示的變量的原始類型,從 TypedReference 中使用 __refvalue 關鍵字獲取參數值,使用 __arglist 訪問參數列表。

    
    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 時,需要 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/arti...http://community.bartdesmet.n...

10. Environment.NewLine
獲取當前環境下的換行字符串。

    Console.WriteLine("NewLine: {0}  first line{0}  second line{0}  third line", Environment.NewLine);

官方文檔 - https://msdn.microsoft.com/en...

11. ExceptionDispatchInfo
保留代碼中的某個被捕獲的異常。你可以使用 ExceptionDispatchInfo.Throw 方法,這個方法在 System.Runtime.ExceptionServices namespace 中。這個方法可用於引發異常並保留原始堆棧的調用過程。

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

被捕獲的異常可以在另一個方法或另一個線程中再次拋出。

官方文檔 - https://msdn.microsoft.com/en...

12. Environment.FailFast()
如果你想在不調用任何 finally 塊或終結器的情況下退出程序,可以使用 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 塊將不會被執行。

官方文檔 - https://msdn.microsoft.com/zh...

13. Debug.Assert&Debug.WriteIf&Debug.Indent
Debug.Assert 用於檢查條件,如果條件是 false,則輸出消息並顯示一個顯示調用堆棧的消息框。

    Debug.Assert(1 == 0, "The numbers are not equal! Oh my god!");

如果斷言在調試模式下失敗,則顯示下面的警報,其中包含指定的消息。

圖片描述

Debug.WriteIf - 如果判斷的結果是 true,則會將有關調試的信息寫入 Listeners 收集中的跟蹤偵聽器內。

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

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

圖片描述

官方文檔:Debug.AssertDebug.WriteIfDebug.Indent / Debug.Unindent

14. Parallel.For&Parallel.Foreach
Parallel.For - 執行一個可並行運行迭代的 for 循環。

    
    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 方法添加兩個整數,並用總和替換第一個整數。

Parallel.Foreach - 執行可並行運行迭代的 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.ForParallel.Foreach

15. IsInfinity
返回一個值,用於表示某一個數是否爲負無窮或正無窮大。

Console.WriteLine("IsInfinity(3.0 / 0) == {0}.", Double.IsInfinity(3.0 / 0) ? "true" : "false");

官方文檔 - https://msdn.microsoft.com/en...

PS:文中提到的.NET開發特性將在 ComponentOne Enterprise .NET控件集中找到應用實例。


本文是由葡萄城技術開發團隊發佈,轉載請註明出處:葡萄城官網

瞭解可嵌入您系統的在線 Excel,請前往 SpreadJS純前端表格控件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章