淺談c#開發(fā)者應(yīng)該了解的15個特性
1. ObsoleteAttribute
ObsoleteAttribute 適用于除組件、模塊、參數(shù)和返回值以外的所有程序元素。將元素標(biāo)記為 obsolete,可以通知用戶該元素將在未來的版本中刪除。
IsError- 設(shè)置為 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# 自動實現(xiàn)的屬性設(shè)置默認(rèn)值
DefaultValueAttribute 可以指定屬性的默認(rèn)值。你可以使用 DefaultValueAttribute 創(chuàng)建任意一個值。成員的默認(rèn)值通常是其初始值。
這個屬性不能用于使用特定的值自動初始化對象成員。因此,開發(fā)者必須在代碼中設(shè)置初始值。
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);
}
}
自動實現(xiàn)的屬性通過反射在類的構(gòu)造函數(shù)中實現(xiàn)初始化。代碼遍歷類的所有屬性,并將它們設(shè)置為默認(rèn)值。
官方文檔-https://msdn.microsoft.com/zh-CN/library/system.componentmodel.defaultvalueattribute.aspx
3. DebuggerBrowsableAttribute
DebuggerBrowsableAttribute 用于確定是否需要以及如何實現(xiàn)在調(diào)試器變量窗口中顯示成員變量。
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. ??運算符
當(dāng)左操作數(shù)非空時,??運算符返回左邊的操作數(shù),否則返回右邊的操作數(shù)。??運算符定義為,將可空類型分配給非空類型時要返回的默認(rèn)值。
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-cn/library/ms173224(v=vs.80).aspx
5. Curry和 Partial 方法
Curry- 在數(shù)學(xué)和計算機科學(xué)中,currying 是一種將函數(shù)的評估轉(zhuǎn)換為多個參數(shù)(或參數(shù)元組)的技術(shù),主要用于評估一系列函數(shù),每個函數(shù)都有一個參數(shù)。
為了通過 C# 實現(xiàn),使用擴展方法的功能。
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關(guān)鍵字進(jìn)行交換。
官方文檔-https://en.wikipedia.org/wiki/Currying
Partial- 在計算機科學(xué)中,Partial應(yīng)用程序(或 Partial功能應(yīng)用程序)是指將一些參數(shù)固定到一個函數(shù)的過程,從而產(chǎn)生另一個更小的函數(shù)。
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/Partial_application
6. WeakReference
弱引用使得在收集器收集對象時,仍允許應(yīng)用程序訪問該對象。如果你需要這個對象,你仍然可以獲得一個強有力的引用,并阻止它被收集。
WeakReferenceTest hugeObject = new WeakReferenceTest(); hugeObject.SharkFirstName = "Sharky"; WeakReference w = new WeakReference(hugeObject); hugeObject = null; GC.Collect(); Console.WriteLine((w.Target as WeakReferenceTest).SharkFirstName);
如果垃圾收集器沒有明確被地調(diào)用,那么仍有很大的可能性弱引用會被分配。
官方文檔-https://msdn.microsoft.com/en-us/library/system.weakreference.aspx
7. Lazy<T>
使用延遲初始化,可推遲創(chuàng)建大型資源密集型對象或執(zhí)行資源密集型任務(wù)時,在程序生命周期內(nèi)創(chuàng)建或執(zhí)行指定類的發(fā)生。
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 類型是一個不可變類型,它表示一個任意大的整數(shù),理論上它的值沒有上限或下限。這種類型與 .NET Framework 中的其他整型類型不同,這種類型具有自身 MinValue 和 MaxValue 屬性指示的范圍。
注意:因為 BigInteger 類型是不可變的,并且因為它沒有上限或下限,所以對于導(dǎo)致 BigInteger 值變得太大的任何操作,都會引發(fā) 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#關(guān)鍵字 (__arglist / __reftype / __makeref / __refvalue)
一些 C# 關(guān)鍵字是沒有官方文檔的,沒有文檔的原因可能是這些關(guān)鍵字沒有經(jīng)過充分測試。但是,這些關(guān)鍵字已被 Visual Studio 編輯器著色并被識別為官方關(guān)鍵字。
你可以使用 __makeref 關(guān)鍵字在變量中創(chuàng)建一個類型化的引用,使用 __reftype 關(guān)鍵字提取由類型化引用表示的變量的原始類型,從 TypedReference 中使用 __refvalue 關(guān)鍵字獲取參數(shù)值,使用 __arglist 訪問參數(shù)列表。
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/articles/20030114.asp和http://community.bartdesmet.net/blogs/bart/archive/2006/09/28/4473.aspx
10. Environment.NewLine
獲取當(dāng)前環(huán)境下的換行字符串。
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.ExceptionServicesnamespace 中。這個方法可用于引發(fā)異常并保留原始堆棧的調(diào)用過程。
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()
如果你想在不調(diào)用任何 finally 塊或終結(jié)器的情況下退出程序,可以使用 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 塊將不會被執(zhí)行。
官方文檔-https://msdn.microsoft.com/zh-cn/library/ms131100(v=vs.110).aspx
13. Debug.Assert&Debug.WriteIf&Debug.Indent
Debug.Assert用于檢查條件,如果條件是 false,則輸出消息并顯示一個顯示調(diào)用堆棧的消息框。
Debug.Assert(1 == 0, "The numbers are not equal! Oh my god!");
如果斷言在調(diào)試模式下失敗,則顯示下面的警報,其中包含指定的消息。

Debug.WriteIf- 如果判斷的結(jié)果是 true,則會將有關(guān)調(diào)試的信息寫入 Listeners 收集中的跟蹤偵聽器內(nèi)。
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");
如果想在調(diào)試輸出窗口中顯示 cake的成分,可以使用上面的代碼。

官方文檔:Debug.Assert,Debug.WriteIf,Debug.Indent / Debug.Unindent
14. Parallel.For&Parallel.Foreach
Parallel.For- 執(zhí)行一個可并行運行迭代的 for 循環(huán)。
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方法添加兩個整數(shù),并用總和替換第一個整數(shù)。
Parallel.Foreach- 執(zhí)行可并行運行迭代的 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
返回一個值,用于表示某一個數(shù)是否為負(fù)無窮或正無窮大。
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#開發(fā)者應(yīng)該了解的15個特性的詳細(xì)內(nèi)容,更多關(guān)于c#開發(fā)者應(yīng)該了解的15個特性的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#操作SQLite數(shù)據(jù)庫方法小結(jié)
這篇文章介紹了C#操作SQLite數(shù)據(jù)庫的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C# Xamarin利用ZXing.Net.Mobile進(jìn)行掃碼的方法
這篇文章主要介紹了C# Xamarin利用ZXing.Net.Mobile進(jìn)行掃碼的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
C# Winform截圖指定控件范圍內(nèi)的圖像的流程步驟
工作所需,需要截圖軟件跑出來的界面上的圖表,但是窗口本身是可以縮放的,圖表也是做的可以跟著窗體大小一起縮放,所以就寫了一個函數(shù),用于截圖圖表容器內(nèi)的圖像,文中有函數(shù)源碼供大家參考,需要的朋友可以參考下2024-10-10

