如何使用 PostSharp 来警告属性在初始化之前是否被访问?
我将如何使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 PostSharp 论坛上的 Gael Fraiteur(感谢 Gael!):
From Gael Fraiteur on the PostSharp forum (thanks Gael!):
您的构造函数如何正确初始化它,然后您就不必担心它?
How about your constructor initializes it properly and then you don't have to worry about it?