我將如何使用PostSharp替換此:如何使用PostSharp來警告如果一個屬性被初始化之前被訪問?
[WarnIfGetButUninitialized]
public int MyProperty {get; set; }
有了這個:
/// <summary>
/// Property which warns you if its value is fetched before it has been specifically instantiated.
/// </summary>
private bool backingFieldIsPopulated = false;
private int backingField;
public int MyProperty {
get
{
if (backingFieldIsPopulated == false)
{
Console.WriteLine("Error: cannot fetch property before it has been initialized properly.\n");
return 0;
}
return backingField;
}
set {
backingField = value;
backingFieldIsPopulated = true;
}
}
更新
我還要補充一點,這是爲了提高代碼的可靠性的好方法。在一個擁有20,000條線路的項目中,很高興知道在使用之前所有事情都已正確初始化。我打算將其用於Debug版本,並在發佈版本中將其刪除,因爲我不想不必要地減慢發行版的速度。
可能重複的[如何通過添加屬性來訪問屬性而無需初始化訪問屬性?](http://stackoverflow.com/questions/9033385/how-to-warn-if-a-property- is-access-without-being-initial-by-adding-an-at) – Caleb 2012-01-30 04:45:47