问题
How would I use PostSharp to replace this:
[WarnIfGetButUninitialized]
public int MyProperty {get; set; }
With this:
/// <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;
}
}
Update
I should also add that this is a good method to increase code reliability. In a project with 20,000 lines, its nice to know that everything is initialized properly before its used. I intend to use this for the Debug build, and remove it in the Release build, because I don't want to slow the end release down unnecessarily.
回答1:
From Gael Fraiteur on the PostSharp forum (thanks Gael!):
You have to use a LocationInterceptionAspect that implements IInstanceScopedAspect. The field 'backingFieldIsPopulated' becomes a field of the aspect.
You can find inspiration in this example:
http://doc.sharpcrafters.com/postsharp-2.1/Content.aspx/PostSharp-2.1.chm/html/d3631074-e131-467e-947b-d99f348eb40d.htm
回答2:
How about your constructor initializes it properly and then you don't have to worry about it?
来源:https://stackoverflow.com/questions/9033577/how-to-use-postsharp-to-warn-if-a-property-is-accessed-before-it-has-been-initia