2017-04-21 59 views
1

我碰到下面的C#代码:是否将“属性”添加到属性类名中作为重大更改?

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class Marker : Attribute 
{ 
} 

我们使用SonarLint和一个of it's rules是说,该类应与字Attribute前缀。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class MarkerAttribute : Attribute 
{ 
} 

我想知道是改变名称MarkerMarkerAttribute重大更改?由于使用该属性时,您可以跳过Attribute部分。另一方面,当在代码中使用属性时,你需要全名,所以它会被打破。

如果这被认为是一个突变,那么最好的方法是什么?因为这样的:使用时

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class MarkerAttribute : Attribute { } 
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] 
public class Marker : MarkerAttribute { } 

会给以下编译错误:

CS1614 '标记' 是 '标记' 和 'MarkerAttribute' 之间不明确; 使用'@Marker'或'MarkerAttribute'

+0

从API的角度来看,它当然是一个突破性的变化,就像每个*类重命名一样。因此,您必须重新编译所有依赖程序集。 – HimBromBeere

回答

2

属性是元数据。对自己的属性什么也不做。当某些代码读取它们时,属性变得很有用。为了读取属性值,代码应该使用属性类名称。例如。通过GetCustomAttribute<T>电话:

Maker maker = yourType.GetCustomAttribute<Maker>(); 

所以重命名属性类的重大更改。为了通过符合性检查规则,您应该重命名属性类。这里没有选择。


请注意,如果您将在这里继承:

public class Marker : MarkerAttribute { } 

然后你会打破完全相同SonarLint统治结束了 - 你会得到两个属性类,其中之一将是不合规的。