这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.Assert,Debug.WriteIf,Debug.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 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);
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...
PS:文中提到的.NET开发特性将在 ComponentOne Enterprise .NET控件集中找到应用实例。
本文是由葡萄城技术开发团队发布,转载请注明出处:葡萄城官网
了解可嵌入您系统的在线 Excel,请前往 SpreadJS纯前端表格控件
这15个特性,身为.NET开发者的你全部都了解吗?相关推荐
- PostgreSQL 15 新特性解读 | 墨天轮优质文章合集
5月19日,PostgreSQL 全球开发组宣布 PostgreSQL 15 的第一个 beta 版本,这一新版本在开发者体验.性能表现等方面都有提升.为了帮助大家更快速了解到PostgreSQL 1 ...
- 阿里云插件新版发布,多特性助力提升开发者体验
好消息!阿里云 Cloud Toolkit 新版本于近日正式发布,推出了面向 IntelliJ 和 Eclipse 两个平台的新款插件,多个重大特性,持续提升开发者体验,本文将带大家快速预览该新版本. ...
- 1024,第 15 届「中国内核开发者大会」 参会指南(议程全剧透)
各位好,第 15 届「中国内核开发者大会」即将开幕,这些参会指南请提前收藏好: 2020「中国内核开发者大会」(以下简称 CLK)将在 2020 年 10 月 24 日举办,线上线下同步进行,线上由 ...
- 值得 .NET 开发者了解的15个特性
本文列举了 15 个值得了解的 C# 特性,旨在让 .NET 开发人员更好的使用 C# 语言进行开发工作. 1. ObsoleteAttribute ObsoleteAttribute 适用于除组件. ...
- c++17新特性_每个开发者都应该了解的一些C++特性
C++ 是一种强大的编程语言,但也因为其复杂性一直让用户望而却步.后来,C++ 决定做出改变,然后发展至今,成了编程社区最受欢迎的语言之一.C++ 有一些新特性非常好用,本文对此进行了介绍,比如 au ...
- 又一低代码平台火了!15 分钟小白轻松开发在线课堂,人人都是开发者时代来了?
据艾瑞咨询统计,2020 年中国在线教育行业市场规模 2573 亿元,过去 4 年的复合增长率达 34.5%.如今在线教育行业如火如荼,亟待一款好的在线教育平台. 此时,不少开发者和教育机构遇到新的难 ...
- java 12 、13、14、15新特性汇总
java 12 Switch 表达式 使用Java 12,switch不仅可以作为语句也可以作为表达式. 无论作为语句或者作为表达式,switch都可以使用传统/简化的作用域和控制流行为. 这将有助于 ...
- android 4.0新的特性(针对开发者)
Android 4.0 是一次重要的平台发布版,为用户和应用程序开发者增加了大量的新特性.在下面我们将讨论的所有新特性和API中,因为它将 Android 3.x 版本中广泛使用的API和全息图像主题 ...
- iOS 15提示“此App的开发者需要更新APP以在此IOS版本上正常工作”
在升级到iOS正式版后,忽然发现原来发布的app忽然提示"此App的开发者需要更新APP以在此iOS版本上正常工作",这个是由于什么问题导致的呢? 其实这个是由于苹果更新了新的签名 ...
最新文章
- mp4格式解析、分割
- java cutdown_Java并发程序入门介绍
- spring管理的类如何调用非spring管理的类
- python菜鸟100例精选
- Qt5.7+Opencv2.4.9人脸识别(六)Tcp,Mysql,3DES,XML综合
- 泥塑课c语言,【C】泥塑课(From http://www.jisuanke.com/)
- VMware产品演示网站
- 【最新首发】创维电视安装第三方软件教程
- Date对象身上的绑定的属性与方法
- ZPL指令打印标签时出现白色窄条的坑
- 校园小说男主是计算机系,十大完本校园小说排行榜 经典好看的青春校园小说...
- 用MATLAB写斐波那契数列
- matlab trangle,Triangle-of-Point-Cloud Matlab 三维点云三角化 不是平面域的三角化 是三维点云三角化 亲身测试绝对可用! - 下载 - 搜珍网...
- M1芯片的mac下的Xcode12以上版本编译报错 this target. for architecture arm64等问题解决方案
- 采药(洛谷-P1048)
- 【N32G457】基于RT-Thread和N32G457的墨水屏日历
- Excel中批量添加批注图片
- 解决pdf打印预览中遇到特殊字符,导出失败问题
- Ununtu 18.04 安装Carla 0.9.13 以及Carla ros bridge 超级避坑指南(更新于2022.10.20)
- 算法竞赛中的线性代数