2017-04-21 57 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統治結束了 - 你會得到兩個屬性類,其中之一將是不合規的。