添加'属性'属性类名称是一个重大变化?

时间:2017-04-21 13:28:17

标签: c# .net attributes

我遇到了以下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
{
}

我想知道将名称Marker更改为MarkerAttribute一个重大改变?由于使用该属性时,您可以跳过Attribute部分。另一方面,在代码中使用属性时,您需要整个名称,因此它将会破坏。

如果这被认为是一个突破性变化,那么处理这个问题的最佳方法是什么?因为:

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

在使用时会出现以下编译错误:

  

CS1614' Marker' Marker'之间的模糊不清和' MarkerAttribute&#39 ;;   使用' @ Marker'或者' MarkerAttribute'

1 个答案:

答案 0 :(得分:2)

属性是元数据。对自己的属性无所作为。当某些代码读取它们时,属性变得有用。为了读取属性值,代码应该使用属性类名。例如。通过GetCustomAttribute<T>致电:

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

因此,重命名属性类是一个重大变化。要通过合规性检查规则,您应该重命名属性类。这里没有选择。

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

public class Marker : MarkerAttribute { }

那么你最终会得到完全相同的SonarLint规则 - 你会得到两个属性类,其中一个属性是不合规的。

相关问题