您的位置:首页 > 编程语言 > C#

C#中隐藏的15大功能

2015-09-01 00:00 525 查看
摘要: 下面列出程序员在C#编程生涯中最喜欢的15个被隐藏的功能,包括完整的解释和代码示例。

有关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());




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

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–如果条件为真,写关于侦听器集中的跟踪监听器调试信息。

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

Debug.Indent/Debug.Unindent–把当前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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 软件开发