本文翻译自:https://www.codeproject.com/Articles/1021335/Top-Underutilized-Features-of-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-us/library/system.obsoleteattribute.aspx

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()]
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-CN/library/system.componentmodel.defaultvalueattribute.aspx

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-CN/library/system.diagnostics.debuggerbrowsableattribute.aspx

4. ?? 运算符

当左操作数非空时,?? 运算符返回左边的操作数,否则返回右边的操作数。?? 运算符定义为,将可空类型分配给非空类型时要返回的默认值。

int? x = null;
int y = x ?? -;
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

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();
Func<int, int> f3 = f2();
Console.WriteLine(f3());

不同方法返回的类型可以与 var 关键字进行交换。

官方文档 - https://en.wikipedia.org/wiki/Currying#/Contrast_with_partial_function_application

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(, );
Console.WriteLine(f4());

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

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-us/library/system.weakreference.aspx

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

8. BigInteger

BigInteger 类型是一个不可变类型,它表示一个任意大的整数,理论上它的值没有上限或下限。这种类型与 .NET Framework 中的其他整型类型不同,这种类型具有自身 MinValue 和 MaxValue 属性指示的范围。

注意:因为 BigInteger 类型是不可变的,并且因为它没有上限或下限,所以对于导致 BigInteger 值变得太大的任何操作,都会引发 OutOfMemoryException。

string positiveString = "";
string negativeString = "-90315837410896312071002088037140000";
BigInteger posBigInt = ;
BigInteger negBigInt = ; 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

9.没有官方文档的C#关键字 (__arglist / __reftype / __makeref / __refvalue)

一些 C# 关键字是没有官方文档的,没有文档的原因可能是这些关键字没有经过充分测试。但是,这些关键字已被 Visual Studio 编辑器着色并被识别为官方关键字。

你可以使用 __makeref 关键字在变量中创建一个类型化的引用,使用 __reftype 关键字提取由类型化引用表示的变量的原始类型,从 TypedReference 中使用 __refvalue 关键字获取参数值,使用 __arglist 访问参数列表。

int i = ;
TypedReference tr = __makeref(i);
Type t = __reftype(tr);
Console.WriteLine(t.ToString());
int rv = __refvalue( tr,int);
Console.WriteLine(rv);
ArglistTest.DisplayNumbersOnConsole(__arglist(, , , , ));

在使用 __arglist 时,需要 ArglistTest 类。

public static class ArglistTest
{
public static void DisplayNumbersOnConsole(__arglist)
{
ArgIterator ai = new ArgIterator(__arglist);
while (ai.GetRemainingCount() > )
{
TypedReference tr = ai.GetNextArg();
Console.WriteLine(TypedReference.ToObject(tr));
}
}
}

参考 - 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 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-us/library/system.runtime.exceptionservices.exceptiondispatchinfo(v=vs.110).aspx

12. Environment.FailFast()

如果你想在不调用任何 finally 块或终结器的情况下退出程序,可以使用 FailFast。


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

如果 i 等于 42,该 finally 块将不会被执行。

官方文档 - https://msdn.microsoft.com/zh-cn/library/ms131100(v=vs.110).aspx

13. Debug.Assert&Debug.WriteIf&Debug.Indent

Debug.Assert 用于检查条件,如果条件是 false,则输出消息并显示一个显示调用堆栈的消息框。

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

如果断言在调试模式下失败,则显示下面的警报,其中包含指定的消息。

Debug.WriteIf -  如果判断的结果是 true,则会将有关调试的信息写入 Listeners 收集中的跟踪侦听器内。

Debug.WriteLineIf( == , "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(, ).ToArray();
long total = ; // Use type parameter to make subtotal a long, not an int
Parallel.For<long>(, nums.Length, () => , (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(, ).ToArray();
long total = ; Parallel.ForEach<int, long>(nums, // source collection
() => , // 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 / ) ? "true" : "false");

官方文档 - https://msdn.microsoft.com/en-us/library/system.double.isinfinity(v=vs.110).aspx

相关阅读:

是什么优化让 .NET Core 性能飙升?
C#开发人员应该知道的13件事情
是什么让C#成为最值得学习的编程语言

值得 .NET 开发者了解的15个特性的更多相关文章

  1. 开发者了解NET的15个特性

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

  2. Java SE 15 新增特性

    Java SE 15 新增特性 作者:Grey 原文地址:Java SE 15 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  3. iOS8 针对开发者所拥有的新特性汇总如下

    iOS8 针对开发者所拥有的新特性汇总如下 1.支持第三方键盘 2.自带网页翻译功能(即在线翻译) 3.指纹识别功能开放:第三方软件可以调用 4.Safari浏览器可直接添加新的插件. 5.可以把一个 ...

  4. 前端开发者进阶之ECMAScript新特性--Object.create

    前端开发者进阶之ECMAScript新特性[一]--Object.create   Object.create(prototype, descriptors) :创建一个具有指定原型且可选择性地包含指 ...

  5. Java 15 新特性:文本块

    大家好,我是DD,今天继续来学点Java的新特性! 假设有这样一个场景,我们需要做一个工具.用来自动生成项目文档,文档可以通过浏览器查看,所以最后产出物肯定是一堆html文件.为了让这些html文件更 ...

  6. Java 15 新特性:隐藏类

    什么是隐藏类 隐藏类,是一种不能被其他类直接使用的类.引入隐藏类的主要目的是给框架来使用,使得框架可以在运行时生成类,并通过反射间接使用它们.可能有点抽象,不要紧,下面我们通过一个例子来直观的认识它! ...

  7. C/C++开发者必不可少的15款编译器+IDE

    1)Best IDE for C/C++ –  kDevelop(http://kdevelop.org/) Kdevelop是一个专为C/C++及其他语言的开源扩展插件IDE.它基于KDevPlat ...

  8. 为OS X开发者准备的15个超棒应用

    几乎所有的开发人员在他们日常的开发工作中都有他们自己不可缺少的工具或实用程序集. 这些工具中的每一个都提供了特定的功能,大多数开发者都已经将他们集成到了其工作流程中. 使用这些工具或实用程序不单单只是 ...

  9. Guava 15新特性介绍

    原文:http://www.javacodegeeks.com/2013/10/guava-15-new-features.html Guava 是众所周知的google出品的开源工具包,十分好用,本 ...

随机推荐

  1. Java文件及文件夹的创建与删除

    功能 这个实例实现了在D盘创建一个文件和文件夹,并删除它们. 函数介绍 createNewFile():当文件不存在时,根据绝对路径创建该文件.     delete():删除文件或者文件夹.     ...

  2. Docker mongodb 3.4 分片 一主 一副 一仲 鉴权集群部署.

    非docker部署 为了避免过分冗余,并且在主节点挂了,还能顺利自动提升,所以加入仲裁节点 为什么要用docker部署,因为之前直接在虚拟机启动10个mongod 进程.多线程并发测试的时候,mong ...

  3. 重温.NET下Assembly的加载过程

    最近在工作中牵涉到了.NET下的一个古老的问题:Assembly的加载过程.虽然网上有很多文章介绍这部分内容,很多文章也是很久以前就已经出现了,但阅读之后发现,并没能解决我的问题,有些点写的不是特别详 ...

  4. 4.2 PCIe体系结构的组成部件

    PCIe总线作为处理器系统的局部总线,其作用与PCI总线类似,主要目的是为了连接处理器系统中的外部设备,当然PCIe总线也可以连接其他处理器系统.在不同的处理器系统中,PCIe体系结构的实现方法略有不 ...

  5. win10系统搭建虚拟机:VMware Workstation Player 12环境+Ubuntu Kylin 16.04 LTS系统

    笔者小白一枚,其实连虚拟机是个啥都不知道...实属惭愧,介于此所以今天倒腾了一下花了一上午就已经搭建好一个VMware Workstation Player 12免费版的,很哈皮,于是赶紧分享一下. ...

  6. VTK显示.vtk格式文件

    void ReadandShowVTKFile () { vtkSmartPointer<vtkRenderer > aRenderer = vtkSmartPointer<vtkR ...

  7. AM335x(TQ335x)学习笔记——触摸屏驱动编写

    前面几篇文章已经通过配置DTS的方式完成了多个驱动的移植,接下来我们解决TQ335x的触摸驱动问题.由于种种原因,TQ335x的触摸屏驱动是以模块方式提供的,且Linux官方内核中也没有带该触摸屏的驱 ...

  8. Caused by: java.sql.SQLException: Operand should contain 1 column(s)

    1.错误描述 [ERROR:]2015-05-05 15:48:55,847 [异常拦截] org.hibernate.exception.DataException: error executing ...

  9. 数据库 事务的特性ACID

    数据库 事务的特性ACID 事务(Transaction)是并发控制的基本单位. 所谓事务,它是一个操作序列,这些操作要么都执行,要么都不执行,它是一个不可分割的工作单位.例如,银行转帐工作:从一个帐 ...

  10. windows驱动程序wdf--KMDF大致框架

    继WDM后微软出了WDF,封装了WDM中的一些基本代码逻辑.本人菜鸟,也不知道本质上有何区别,只觉得是多了Wdf开头的函数,基本的编程框架上有点出入. KMDF是WDF的内核级部分,为了理清KMDF的 ...