注意 如何從system.attribute類中繼承 以及如何使用建構函式和屬性來定義attribute引數
可以在vb類中使用該attribute 方法如下
public class fred
...
end class
在c++中 可以使用attribute的 attribute 來建立乙個託管類或者結構
以代表乙個自定義attribute 注意這個類不必從system.attribute中繼承
[attribute(target)]
public __gc class author ;
如果 attribute 要用於其他 assembly那麼類必須是公共的target
引數是system.attributetargets 列舉的乙個引數 如前面表 2.5 所示 在 attribute 類中 建構函式用於指定位置引數 而資料成員和屬性則用於實現命名引數 下面是author attribute的c++**
[attribute(class)] public __gc class author __property string* get_moddate () __property string* set_moddate (string* date) author(string* name) }; 可以將該attribute加入到乙個類中 如下所示 [author("julian", date="21/12/00")] public __gc class foo ; 可以看到 因為data是乙個命名引數 它由關鍵字指定 並且位於引數列表的末尾 在c#中 建立attribute的方法是類似的 但有兩點不同 [attributeusage(attributetargets.class)] public class author : system.attribute } public string moddate set } author(string name) }; 第乙個區別是 attribute類從system.attribute繼承而來 而c++中則不需要任何繼承第二個區別是 attributeusage attribute用於控制該attribute的使用範圍 除此之外 **在結構上是很類似的 使用建構函式實現位置引數 使用屬性實現命名引數
2.2.19 查詢attribute
儘管大多數attribute都由編譯器建立 並由clr使用 但是有時候程式設計師還需要知道某些項處理特定attribute的範圍 並且能夠檢查這些attribute 為了找到有關 attribute 需要了解 system.type 類 type 是表示類 介面 屬性 值型別以及列舉等型別定義的一種類 它能夠找出許多關於型別及其屬性的詳細資訊 但是 使用者只需要知道如何使用類來獲取這些attribute資訊即可 注意 如果了解c++ 可以考慮使用rtti將會有所幫助 下面考察 vb中是如何檢索attribute資訊的例項 並對該**進行分析 仍然使用前一節的author attribute例項 public class foo ... end class 獲得乙個type物件以表示foo類 而後查詢該類 可以知道foo類是否具有乙個author attribute
在c#中實現該操作幾乎是完全相同的
usingsystem;
...
type tf
=typeof
(foo);
object
atts
=tf.getcustomattributes(
true
); foreach
(object
o in
atts)
第一件事就是 使用typeof操作符獲取乙個所要查詢的類的type物件
而後可以使用getcustomattributes()方法來獲取一組該物件所支援的自定義attribute的引用列表
因為將返回普通物件引用的陣列 因此需要檢查物件的型別 以確認它們中是否有 author 項
注意gettype()方法的使用 它將從物件引用中返回乙個 type 物件
這與 typeof 操作符相對應後者從類名稱中返回乙個 author 屬性
一旦對該類找到了乙個 author 屬性 就可以檢索該引數
C 獲取xml屬性名稱
工作需要,讀取乙個超大量的xml檔案,從xml檔案中,讀取節點,以及節點下的屬性名稱,用屬性名稱進行建表操作。在網上查詢資料未果,於是自己尋找辦法。在xmlelement類下有乙個屬性是attributes,返回值為xmlattributecollection,節點element的屬性儲存在xmla...
C 獲取屬性的description總結
現有乙個結構體 public struct desc set 以下省略 獲取description string str desc desc new desc 不用反射 獲取屬性的特性 propertydescriptor pd typedescriptor.getproperties typeof...
C 如何獲取檔案屬性
c 如何獲取檔案屬性,stat 系統呼叫系列包括了fstat stat和lstat,它們都是用來返回 相關檔案狀態資訊 的,三者的不同之處在於設定原始檔的方式不同。stat系統呼叫系列包括了fstat stat和lstat,它們都是用來返回 相關檔案狀態資訊 的,三者的不同之處在於設定原始檔的方式不...