浅谈c#开发者应该了解的15个特性

本文列举了15个值得了解的C#特性,旨在让.NET开发人员更好的使用C#语言进行开发工作。

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的成分,可以使用上面的代码。

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.For和Parallel.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

以上就是浅谈c#开发者应该了解的15个特性的详细内容,更多关于c#开发者应该了解的15个特性的资料请关注得得之家其它相关文章!

本文标题为:浅谈c#开发者应该了解的15个特性