如何使用PostSharp警告,如果它已被初始化之前一个属性被访问? [英] How to use PostSharp to warn if a property is accessed before it has been initialized?

查看:127
本文介绍了如何使用PostSharp警告,如果它已被初始化之前一个属性被访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用PostSharp替换此:

How would I use PostSharp to replace this:

[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;
    }
}       

更新

我还要补充一点,这是增加code可靠性的好方法。在20000线一期工程,它很高兴知道,一切都正确的使用之前进行初始化。我打算用本作的调试版本,并在发布版本中删除,因为 我不想放慢月底发布下不必要的。

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.

推荐答案

从盖尔Fraiteur上PostSharp论坛(感谢盖尔!):

From Gael Fraiteur on the PostSharp forum (thanks Gael!):

您必须使用LocationInterceptionAspect实现   IInstanceScopedAspect。本场backingFieldIsPopulated成为   领域方面的。

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:

<一个href="http://doc.sharpcrafters.com/postsharp-2.1/Content.aspx/PostSharp-2.1.chm/html/d3631074-e131-467e-947b-d99f348eb40d.htm" rel="nofollow">http://doc.sharpcrafters.com/postsharp-2.1/Content.aspx/PostSharp-2.1.chm/html/d3631074-e131-467e-947b-d99f348eb40d.htm

这篇关于如何使用PostSharp警告,如果它已被初始化之前一个属性被访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆