How to use PostSharp to warn if a property is accessed before it has been initialized?

∥☆過路亽.° 提交于 2020-01-15 09:07:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!