2013-02-25 59 views
2

我想知道C#中的屬性是如何工作的。我知道如何聲明一個屬性或如何創建一個屬性。我想知道如何在特定屬性上生成特定行爲。我應該使用反射嗎?C#中使用反射屬性?

+6

是................... – 2013-02-25 10:12:44

回答

2

除非您使用AOP框架(例如PostSharp),否則直接影響您的代碼的屬性很少,而且它們只是一些內置屬性。您無法將行爲添加到自定義屬性。同樣的:是的,你必須使用反射來測試你的自定義屬性的存在和/或實現屬性(只是檢查存在比實現它們更便宜)。

如果您正在做這件事,您可能需要考慮緩存通過屬性獲取的信息,這樣您就不需要每次需要元數據時都使用反射。

0

是的,您使用反射來檢查類型或成員是否具有自定義屬性。 這是一個示例,它獲取給定類型的MyCustomAttribute實例。它會返回第一個MyCustomAttribute聲明或null(如果找不到):

private static MyCustomAttribute LookupMyAttribute(Type type) 
{ 
    object[] customAttributes = type.GetCustomAttributes(typeof(MyCustomAttribute), true); 
    if ((customAttributes == null) || (customAttributes.Length <= 0)) 
     return null; 

    return customAttributes[0] as MyCustomAttribute ; 
} 
1

是的。假設你有一個對象o並且你想檢查你的屬性的存在。所有你需要做的是:

Type t = o.GetType(); 
     object[] attributes = t.GetCustomAttributes(typeof(MyCustomAttribute)); 
     if (attributes.Length>0){ 
      MyCustomAttribute a = attributes[0] as MyCustomAttribute; 
      //use your attribute properties to customize your logic 
     } 
+2

如果你想檢查的屬性* *存在,那麼'屬性.IsDefined'明顯便宜 – 2013-02-25 10:16:25

+0

我同意...如果您需要使用屬性屬性,請使用我的代碼。 – 2013-02-25 10:16:54