【问题标题】:How to use PostSharp to warn if a property is accessed before it has been initialized?如何使用 PostSharp 警告是否在初始化之前访问了属性?
【发布时间】:2012-01-27 12:59:27
【问题描述】:

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

【问题讨论】:

标签: c# .net visual-studio postsharp


【解决方案1】:

来自 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

【讨论】:

【解决方案2】:

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

【讨论】:

  • 当然,如果您正在处理一个 100 行的项目。如果您正在处理一个 50,000 行的项目,这种技术在开发阶段会捕获可能由于人为错误而漏网的错误。这种技术也适用于检查遗留代码。它是篮子中的一项小技术,有助于生成健壮的企业级代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 2023-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多