13.???? 定義自定義屬性參數的訪問屬性
翻譯概述:
一個比較無聊的規則,實在看不出在什么情況下,一個開發者會做出違反這條規則的設計。沒有別的內容,只是說應該為自定義特性的構造函數中的參數提供一個相關的屬性去讀取它們的值。
一個讓我比較費解的規則,即沒有看出其中所傳達的設計思想,也沒發現任何優秀的設計技巧。
原文引用:
Define accessors for attribute arguments<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
Rule Description
Attributes can define mandatory arguments that must be specified when applying the attribute to a target. These are sometimes called positional arguments because they are supplied to attribute constructors as positional parameters. For every mandatory argument, the attribute should also provide a corresponding read-only property so that the value of the argument can be retrieved at execution time. This rule checks to see that for each constructor parameter, you have defined the corresponding property. Attributes can also define optional arguments, called named arguments. These arguments are supplied to attribute constructors by name and should have a corresponding read/write property. For mandatory and optional arguments, the corresponding properties and constructor parameters should use the same name but different casing. (Properties use Pascal casing, and parameters use camel casing.) How to Fix Violations
To fix a violation of this rule, add a read-only property for each constructor parameter that does not have one. When to Exclude Messages
Exclude a message from this rule if you do not want the value of the mandatory argument to be retrievable. Example Code
The following example shows two attributes that define a mandatory (positional) parameter. The first implementation of the attribute is incorrectly defined. The second implementation is correct. [Visual Basic] ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() [C#] ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() Related Rules
Avoid unsealed attributes See Also
Attribute Usage Guidelines |
引起的原因:
沒有為一個自定義特性(Attribute)的構造函數中的所有參數定義相應的屬性來訪問這些參數。
描述:
自定義特性可以定義一組強制參數,當將特性應用到目標上時,必須指定這些參數。因為他們被定義為特性的構造函數的位置參數(非命名參數),通常稱它們為位置參數。對于每一個強制參數,自定義特性應該同時提供一個相關的制度屬性,這樣,才能在需要的時候獲得這些參數的值。這條規則檢查你是否為每一個參數定義了相關屬性。
自定義特性也可以定義可選參數,稱之為命名參數。在自定義特性的構造函數中可以使用名字指定它們的值。應該為它們定義可讀可寫屬性。
對于強制的和可選的參數,他們相關的屬性應該和構造函數參數有類似的名字,僅僅使用大小寫區分它們。(屬性使用Pascal命名規則,參數使用駱峰命名規則)
修復:
為構造函數中的每一個參數提供一個只讀屬性。
例外:
如果你不打算獲得強制參數的值,可以忽略這條規則。
例程:
原文中給出了兩個自定義特性類(分別給出了使用VB.NET和C#的實現),它們都定義了一個強制參數。其中第一個自定義特性類違反了這條規則,沒有為強制參數實現相關的屬性。第二個自定義特性類修復了這個問題。