.NET 中 15 个未充分利用的特性






4.81/5 (232投票s)
我最喜欢的 .NET 中未充分利用的特性列表。包含对其作用的完整解释以及 C# 代码示例。
引言
自从我写下第一行 C# 代码以来,我一直热衷于 C# 语言的优雅和美感。我总是在空闲时间阅读有关它的不同文章和书籍。在这里,我将与大家分享我最喜欢的几十个 C# 中**未充分利用**的特性(**经常被遗忘/有趣的/神秘的/隐藏的**)。
在收到关于文章原标题“C# 中 15 个隐藏特性”的众多评论后,我决定将其更改为当前标题。感谢大家的建议。我最初的意图并不是误导大家。文章的最初想法来自 Stack Overflow 上一个标题类似的讨论,所以我决定不更改它,因为人们已经熟悉这个主题。但为了所有过去和未来的批评者,我正在更改标题。
您可以在评论中分享您最喜欢但不太为人所知的框架特性。我将在该系列的未来第二部分中收录它们。此外,您可以在文章末尾找到的投票中,为您最喜欢的 .NET 隐藏特性投票。
目录
- ObsoleteAttribute
- 通过 DefaultValueAttribute 为 C# 自动实现的属性设置默认值
- DebuggerBrowsableAttribute
- ?? 运算符
- 柯里化和局部方法
- WeakReference
- Lazy
- 大整数
- __arglist __reftype __makeref __refvalue
- Environment.NewLine
- ExceptionDispatchInfo
- Environment.FailFast
- Debug.Assert、Debug.WriteIf 和 Debug.Indent
- Parallel.For 和 Parallel.Foreach
- IsInfinity
.NET 中未充分利用的特性
1. ObsoleteAttribute
ObsoleteAttribute
适用于除程序集、模块、参数和返回值之外的所有程序元素。将元素标记为过时,是告知用户该元素将在产品的未来版本中移除。
Message
属性包含一个 string
,当使用属性赋值时,该字符串将显示。建议在此描述中提供一个变通方法。
**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(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);
}
}
自动实现的属性通过反射在类的构造函数中初始化。代码遍历类的所有属性,如果存在 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. ?? 运算符
我最喜欢的“C# 中未充分利用的特性”之一是 ??
运算符。我在代码中大量使用它。
在该系列的下一部分中,讨论了空合并运算符 ?? 或 GetValueOrDefault 方法哪个更快。结果,我做了研究,你可以在**这里**找到它。
**?? 运算符**如果左操作数不为 null
,则返回左操作数,否则返回右操作数。可空类型可以包含值,也可以未定义。**?? 运算符**定义了当可空类型赋值给不可空类型时要返回的默认值。
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
– 在数学和计算机科学中,柯里化是将一个接受多个参数(或参数元组)的函数的求值转换为求值一系列函数的技术,每个函数只有一个参数。
为了通过 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/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);
}
}
局部扩展方法的用法比柯里化方法更直接。
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. 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 = "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
获取为此环境定义的换行符 string
。
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();
}
捕获的异常可以在另一个方法甚至另一个线程中再次抛出。
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
– 检查条件;如果条件为 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");
如果要在调试输出窗口中显示蛋糕的配料,可以使用上面的代码。
**官方文档:**Debug.Assert、Debug.WriteIf、Debug.Indent/Debug.Unindent
14. Parallel.For & Parallel.Foreach
我不确定我们是否能将这些添加到 .NET 中未充分利用的特性列表中,因为它们在 TPL (任务并行库) 中被大量使用。然而,我在这里列出它们是因为我非常喜欢它们,并在我的多线程应用程序中利用它们的力量。
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
(Visual Basic 中的 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# 系列到目前为止
- 实现复制粘贴 C# 代码
- MSBuild TCP IP 日志记录器 C# 代码
- Windows 注册表读写 C# 代码
- 运行时更改 .config 文件 C# 代码
- 通用属性验证器 C# 代码
- Reduced AutoMapper - Auto-Map 对象速度提高 180%
- C# 6.0 中的 7 个新酷炫功能
- 代码覆盖率类型 - C# 示例
- 通过 MSTest.exe 包装应用程序重新运行失败的 MSTest
- 高效安排 Visual Studio 中 using 语句的提示
- 19 个必备 Visual Studio 键盘快捷键 – 第 1 部分
- 19 个必备 Visual Studio 键盘快捷键 – 第 2 部分
- 在 Visual Studio 中根据构建配置指定程序集引用
- .NET 中 15 个未充分利用的特性
- .NET 中 15 个未充分利用的特性 第 2 部分
- 轻松在 C# 中格式化货币的巧妙技巧
- 正确断言 DateTime MSTest NUnit C# 代码
- 哪个更快 - 空合并运算符或 GetValueOrDefault 或条件运算符
- 用于增强单元测试的基于规范的测试设计技术
- 在 C# 中使用 Lambda 表达式获取属性名称
- 使用 C# 的 9 大 Windows 事件日志技巧
如果您喜欢我的出版物,请随时**订阅**。
此外,点击这些分享按钮。**谢谢!**
源代码
**注意**:此帖子中嵌入了一个投票,请访问网站参与此帖子的投票。
帖子 .NET 中 15 个未充分利用的特性 最早出现在 Automate The Planet。
所有图片均从 DepositPhotos.com 购买,不可免费下载和使用。