有关C#中15大隐藏的顶级功能的第一个帖子是出现在Automate The Planet上。下面列出程序员在C#编程生涯中最喜欢的被隐藏的C#功能,当然包括完整的解释和代码示例。

1. ObsoleteAttribute

ObsoleteAttribute适用于除组件,模块,参数和返回值的所有程序元素。标记过时元素,并通知用户该元件将在产品的未来版本中删除。
Message属性包含一个当assignee属性后将显示的字符串。
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());

C#警告示例

官方文档:https://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx

2.通过DefaultValueAttribute设置C# Auto-implemented属性默认值

DefaultValueAttribute指定了属性的默认值。你可以创建DefaultValueAttribute为任何价值,成员的默认值通常是它的初始值。
该属性不会导致成员被自动指定的值初始化。因此,你必须在代码中设置初始值。

public class DefaultValueAttributeTest
{public DefaultValueAttributeTest(){// Use the DefaultValue propety 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);}
}

Auto-implemented属性在类中通过反射构造函数初始化。代码通过类的所有属性进行迭代,并且如果DefaultValueAttribute存在,就将它们设置为默认值。
官方文档:https://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx

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

如果你在代码中使用示例类,那么尝试通过调试器(F11)执行。

DebuggerBrowsableTest.SquirrelFirstNameName = "Hammy";
DebuggerBrowsableTest.SquirrelLastNameName = "Ammy";

官方文档:https://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx

4. ?? Operator

?? Operator是程序猿最喜欢的C#隐藏功能之一,经常在代码里用到它。
如果左边的操作数不为空,?? Operator返回左边的操作数,,否则将返回右边的。可空类型可以包含一个值,也可以是不确定的。当可空类型分配给非可空类型时?? Operator定义返回默认值。

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/en-us/library/ms173224(v=vs.80).aspx

5. Curry和Partial方法

Curry-在数学和计算机科学中,柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术。
要想通过C#实现,就要用到Curry扩展方法。

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/Currying#/Contrast_with_partial_function_application
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));

同样,不同类型的代理可通过var关键字来声明。
官方文档:https://en.wikipedia.org/wiki/Partial_application

6. Weak Reference

Weak Reference允许垃圾收集器收集对象,同时还允许应用程序访问的对象。如果需要该对象,仍可通过强引用获取,并防止它被收集。

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 = "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-us/library/system.numerics.biginteger(v=vs.110).aspx

9.未公开的C#关键字__arglist __reftype __makeref __refvalue

我不确定这些能不能被当作C#中隐藏的功能,因为它们没有被公开,因此应该谨慎使用。没有一个关于原因的文档,也许是因为没有经过充分的测试。然而,它们由Visual Studio编辑器着色,并且识别为官方关键字。
你可以通过使用__makeref关键字创建变量的类型引用。由类型引用表示的变量的原始类型可以使用__reftype关键字提取。最后,该值可以从使用__refvalue关键字从TypedReference获得。__arglist与关键字params具有相似的行为-可以访问参数列表。

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.asp 和http://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命名空间中找到。这种方法可用于引发异常和保留原始堆栈跟踪。

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

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

Debug.Assert-检查条件;如果条件为假,输出的消息并显示调用堆栈的消息框。

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

如果断言在调试模式失败,则显示包含指定的消息的警告,如下:

失败提示

Debug.WriteIf&ndash;如果条件为真,写关于侦听器集中的跟踪监听器调试信息。

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

Debug.Indent/Debug.Unindent&ndash;把当前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.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<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

转自:http://www.evget.com/article/2015/8/28/22602.html

转载于:https://my.oschina.net/u/2417198/blog/500240

C#中隐藏的15大功能相关推荐

  1. 华为手机隐藏的3大功能,现在才知道,怪不得别人手机这么好用

    使用过华为手机的用户都会有一个感触,手机里隐藏着无限好用功能,不过这些功能都是不容易被发现,并且隐藏极深.话不多说赶紧看看都是那些功能吧! 文件加密 大家都在手机中保存过文件,简单的将文件保存在手机中 ...

  2. 最新开源微信小程序一键开发平台源码 支持15大功能模块+完整前后端+搭建教程

    分享一个开源微信小程序一键开发综合平台源码,系统支持15大小程序功能模块,涉及各行各业,含完整前后端+详细搭建部署教程. 系统特色功能一览: 1.全新重构升级功能后端文件和前端文件: 2.整套源码已经 ...

  3. 全功能版SEO动态寄生虫-15项功能霸屏排名版

    2019全功能版SEO动态寄生虫泛目录,那么值得一说的,寄生虫同样有Shell站群功能,通过不同的Shell生成,客户端会返回URL数据到服务器端,服务器端记录下此次的繁殖数据,在下次不同的Shell ...

  4. 蚂蚁集团强化与阿里隔离:马云不再是实际控制人;iPhone 15 Pro将独占6大功能;Linux 4.9正式EOL|极客头条

    「极客头条」-- 技术人员的新闻圈! CSDN 的读者朋友们早上好哇,「极客头条」来啦,快来看今天都有哪些值得我们技术人关注的重要新闻吧. 整理 | 梦依丹 出品 | CSDN(ID:CSDNnews ...

  5. oppo计算机隐藏功能计算星座,OPPO手机隐藏的5大神级功能!全部知道手机算没白买,你知道几个...

    原标题:OPPO手机隐藏的5大神级功能!全部知道手机算没白买,你知道几个 OPPO手机在国内数一数二,今年还特别推出了OPPO R17系列的新年版本,大红配色和祥云.猪猪图案,和新年正好应景.但是不知 ...

  6. Reporting Services 2016中不推荐使用的5大功能

    It's not often that I write negative articles surrounding SQL Server's latest release but ever since ...

  7. 苹果手机计算机怎么变高级,苹果手机中隐藏的7个高级功能

    苹果手机一直都是非常受到群众的欢迎的,因为很多人觉得使用苹果手机和使用安卓手机给自己的感觉是不一样的,而且苹果手机的使用寿命比安卓手机长.但是很多人觉得苹果手机上的功能和安卓手机没有区别,其实只是你没 ...

  8. 魅族 计算机 隐藏,魅族Flyme中隐藏的功能,90%的人都不知道,不用白买了

    原标题:魅族Flyme中隐藏的功能,90%的人都不知道,不用白买了 智能手机已经逐渐的走进人们的生活,成为了人们每天随身携带且使用频率最高的设备,自然里面存有很多重要的资料.但是即使大家在小心的使用用 ...

  9. Paper:《Hidden Technical Debt in Machine Learning Systems—机器学习系统中隐藏的技术债》翻译与解读

    Paper:<Hidden Technical Debt in Machine Learning Systems-机器学习系统中隐藏的技术债>翻译与解读 导读:机器学习系统中,隐藏多少技术 ...

最新文章

  1. CCNA认证指南note 01
  2. [java进阶]1.Java读取txt文件和写入txt文件
  3. [爬虫-python] scrapy框架入门实例-百度贴吧
  4. Win03+IIS6 部署.NetFramework4(ASP.NET4)的一点小经验
  5. RuoYi框架使用手册
  6. php数组重置,php 重置数组索引,兼容多维数组
  7. Python-模块导入-63
  8. crmeb安装教程说明
  9. 【渝粤题库】陕西师范大学165102管理心理学 作业(高起专)
  10. win10去掉快捷方式小箭头_win7去除快捷方式小箭头的方法教程
  11. UltraVNC,UltraVNC软件可以用来干嘛?
  12. Arduino上U8g2库自定义中文库的经历
  13. 【项目管理/PMP/PMBOK第六版/新考纲】计算题! 项目章程/变更/工作绩效报告/项目范围说明书/工作分解结构WBS/最小浮动时间/挣值分析/采购
  14. 计算机在当今社会的重要性
  15. 【转载】linux修改文件的所有者权限[root权限更改为用户权限]
  16. 怎么批量设置EDIUS中的图片持续时间
  17. 常用三角函数的无穷级数乘积公式推导详细过程与图形展示
  18. 【数据结构】节点和结点,到底怎么区分?
  19. Lua——迭代器的使用、pairs 和 ipairs区别
  20. PostgreSQL安装之后,打开pgAdmin4后,点击servers下方没有任何内容的情况

热门文章

  1. java ActionListener 接口如何判断触发事件来源。getSource()和 getActionCommand()
  2. OsgEarth加载DEM(数字高程模型)
  3. BN/Batch Norm中的滑动平均/移动平均/Moving Average
  4. cerr与cout的区别
  5. GL.iNet MT1300 双频千兆无线路由器
  6. 60.【Java 进阶】
  7. 怎么防止解决百度转码问题
  8. 安卓系列之 kotlin 项目实战--基础 demo
  9. 论文写作学习之引言章节撰写(学习深度之眼课程笔记,侵删)
  10. 英飞凌TC387学习