如何使用 PostSharp 来警告属性在初始化之前是否被访问?

发布于 2024-12-29 17:51:40 字数 880 浏览 0 评论 0原文

我将如何使用 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 行的项目中,很高兴知道所有内容在使用之前都已正确初始化。我打算将其用于调试版本,并在发布版本中将其删除,因为 我不想不必要地减慢最终版本的速度。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

糖粟与秋泊 2025-01-05 17:51:40

来自 PostSharp 论坛上的 Gael Fraiteur(感谢 Gael!):

您必须使用实现以下功能的 LocationInterceptionAspect
IInstanceScopedAspect。字段“backingFieldIsPopulated”变为
方面的领域。

您可以在此示例中找到灵感:

http://doc.sharpcrafters.com/postsharp-2.1/Content.aspx/PostSharp-2.1.chm/html/d3631074-e131-467e-947b-d99f348eb40d.htm

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

芯好空 2025-01-05 17:51:40

您的构造函数如何正确初始化它,然后您就不必担心它?

How about your constructor initializes it properly and then you don't have to worry about it?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文