C#中隱藏的15大頂級功能(2/2)

9.未公開的C#關鍵字__arglist __reftype __makeref __refvalue
我不肯定這些能不能被看成C#中隱藏的功能,由於它們沒有被公開,所以應該謹慎使用。沒有一個關於緣由的文檔,也許是由於沒有通過充分的測試。然而,它們由Visual Studio編輯器着色,而且識別爲官方關鍵字。
你能夠經過使用__makeref關鍵字建立變量的類型引用。由類型引用表示的變量的原始類型可使用__reftype關鍵字提取。最後,該值能夠從使用__refvalue關鍵字從TypedReference得到。__arglist與關鍵字params具備類似的行爲-能夠訪問參數列表。html

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

從第一個可選參數開始備註ArgIterator對象列舉的參數列表,這是專門爲了與C/ C ++編程語言的使用提供的。
相關文檔:http://www.nullskull.com/articles/20030114.asphttp://community.bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx多線程

10. Environment.NewLine
獲取此環境中定義的換行符的字符串。編程語言

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
表示在代碼中特定點捕獲的異常。你可使用ExceptionDispatchInfo.Throw方法,能夠在System.Runtime.ExceptionServices命名空間中找到。這種方法可用於引起異常和保留原始堆棧跟蹤。oop

ExceptionDispatchInfo possibleException = null;

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

if (possibleException != null)
{
    possibleException.Throw();
}

捕獲到的異常能夠經過另外一種方法再次被拋出,甚至在另外一個線程拋出。
官方文檔:https://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo(v=vs.110).aspx測試

12. Environment.FailFast()
若是要退出程序而無需調用任何finally塊或終結器那麼使用FailFastspa

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/en-us/library/ms131100(v=vs.110).aspx.net

13. Debug.Assert & Debug.WriteIf & Debug.Indent
Debug.Assert-檢查條件;若是條件爲假,輸出的消息並顯示調用堆棧的消息框。線程

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

若是斷言在調試模式失敗,則顯示包含指定的消息的警告,以下:
debug-assert-fail-alert.jpg
Debug.WriteIf–若是條件爲真,寫關於偵聽器集中的跟蹤監聽器調試信息。

Debug.WriteLineIf(1 == 1, "This message is going to be displayed in the Debug output! =)");

Debug.Indent/Debug.Unindent–把當前entLevel加一。

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

若是要顯示在調試輸出窗口的各組分,可使用上面的代碼。
debug-indent-example.jpg
官方文檔:Debug.Assert, Debug.WriteIf, Debug.Indent/Debug.Unindent

14. Parallel.For & Parallel.Foreach
我不肯定是否能夠把它歸類到C#中被隱藏的功能,由於在TPL (Task Parallel Library)常常用到。然而,我把它放這兒是由於我很是喜歡在多線程應用程序中用到它。
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(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(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-us/library/system.double.isinfinity(v=vs.110).aspx

轉自:慧都控件網

相關文章
相關標籤/搜索