c# 是一種命令式語言,但像所有命令式語言一樣,它具有某些聲明性元素。例如,通過將類中的方法聲明為 public、protected、internal、protected internal 或 private,指定它的可訪問性。c# 使此功能一般化,以便程序員可以創造出一種新的聲明性信息,將此聲明性信息附加到各種程序實體,并在運行時檢索此聲明性信息。程序通過定義和使用屬性(第 17 節)來描述這類額外的聲明性信息。
例如,一個框架也許會定義一個可放置在程序元素(如類和方法)上的 helpattribute 屬性,使開發人員能夠提供從程序元素到其文檔的映射。示例
using system;
[attributeusage(attributetargets.all)]
public class helpattribute: attribute
{
public helpattribute(string url) {
this.url = url;
}
public string topic = null;
private string url;
public string url {
get { return url; }
}
}
定義了一個名為 helpattribute 的屬性類,它具有一個定位參數 (string url) 和一個命名參數 (string topic)。正如第 17.1 節中所解釋的,該屬性可以通過它的完整名稱 helpattribute 或通過它的隱式簡稱 help 引用。定位參數由該屬性類的公共實例構造函數的形參定義,命名參數則由屬性類的公共非靜態讀寫字段和對應的屬性定義。
示例
[help("http://www.microsoft.com/.../class1.htm")]
public class class1
{
[help("http://www.microsoft.com/.../class1.htm", topic = "f")]
public void f() {}
}
顯示 help 屬性的幾種用法。
在運行時可以利用反射支持檢索給定程序元素的屬性信息。示例
using system;
class test
{
static void main() {
type type = typeof(class1);
object[] arr = type.getcustomattributes(typeof(helpattribute), true);
if (arr.length == 0)
console.writeline("class1 has no help attribute.");
else {
helpattribute ha = (helpattribute) arr[0];
console.writeline("url = {0}, topic = {1}", ha.url, ha.topic);
}
}
}
檢查 class1 是否具有 help 屬性,如果具有該屬性,則寫出關聯的 topic 和 url 值。
,歡迎訪問網頁設計愛好者web開發。新聞熱點
疑難解答