Kha*_*uez 2 .net c# attributes
今天,我正在使用FXCop清理我的一些代码,它抱怨我遇到这种违规的属性类.
CA1019: Define accessor for attribute argument.
Run Code Online (Sandbox Code Playgroud)
在这个页面上,http://msdn.microsoft.com/en-us/library/ms182136.aspx有更多的信息,但我仍然没有得到这个的原因,因为在我看来它更冗长,更不相关.
它给出了两个代码样本.
using System;
namespace DesignLibrary
{
// Violates rule: DefineAccessorsForAttributeArguments.
[AttributeUsage(AttributeTargets.All)]
public sealed class BadCustomAttribute :Attribute
{
string data;
// Missing the property that corresponds to
// the someStringData parameter.
public BadCustomAttribute(string someStringData)
{
data = someStringData;
}
}
// Satisfies rule: Attributes should have accessors for all arguments.
[AttributeUsage(AttributeTargets.All)]
public sealed class GoodCustomAttribute :Attribute
{
string data;
public GoodCustomAttribute(string someStringData)
{
data = someStringData;
}
//The constructor parameter and property
//name are the same except for case.
public string SomeStringData
{
get
{
return data;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么需要SomeStringData属性.someStringData不是一个参数吗?如果它已经存储在另一个属性中,为什么需要拥有自己的属性?
实际上,我看起来有点不同.
[AttributeUsage(AttributeTargets.Property)]
public sealed class ExampleAttribute : Attribute
{
public ExampleAttribute(string attributeValue)
{
this.Path = attributeValue;
}
public string Name
{
get;
set;
}
// Add to add this to stop the CA1019 moaning but I find it useless and stupid?
public string AttributeValue
{
get
{
return this.Name;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用公共autoproperty而不是私有字段,我必须添加最后一部分以使警告停止,但我没有看到这一点,它还为此类添加了另一个公共字段,这是多余的,似乎不太干净.
也就是说,我认为这个警告是出于某种原因而提出的,所以我错过了什么理由呢?
提前致谢.