我想一些技術來自動替換下面的代碼:如何通過添加屬性來警告未經初始化訪問屬性?
[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;
}
}
我寧願在編譯時有效的解決方案,因爲反射緩慢。我知道面向方面編程(AOP)會這樣做(例如PostSharp和CciSharp),但如果有其他方法可以實現這一點,我會很感興趣。
更新
參見How to use PostSharp to warn if a property is accessed before it has been initialized?其具有鏈接到演示使用PostSharp的技術中的一些示例代碼。
我說你最簡單的選擇是使用PostSharp或統一的IoC它可以做有限的AOP。 – 2012-01-27 12:46:11