2014-08-31 67 views
0

意向:自定義屬性構造函數何時執行?

我寫一個使用大部分這些枚舉存在於數據庫中的表太多次枚舉業務應用。問題出現在維護時,其中一個團隊成員或後期開發人員在兩個地方之一更改枚舉成員值,使枚舉未被同步。爲了解決這個問題,我試圖創建一個自定義枚舉屬性,當它發現一個枚舉值不同步時拋出一些異常。

實現:

[AttributeUsage(AttributeTargets.Enum)] 
public class EnumSyncAtrribute : Attribute 
{ 

    public EnumSyncAtrribute(Type databaseAccessType, Type enumType)) 
    { 

     // Code that uses that databaseAccessType to access the database to get 
     // enum values then compare it to values of enumType , goes here. 

    } 
} 

然後瞄準枚舉標記如下

[EnumSyncAtrribute(typeof(MyDataBaseAccess), typeof(MyEnum))] 
public enum MyEnum 
{ 
    value1 = 0, 
    value2 = 1, 
    value3 = 2 
} 

問題:

問題是這樣的屬性構造從不執行!我試過用類替換枚舉,發現它執行得很好,但是使用枚舉,不行!

問題是,當自定義屬性用於枚舉時,它們的構造函數何時執行?

+0

的可能重複的[屬性類不調用構造函數(http://stackoverflow.com/questions/2470164/attribute-class-not-calling-constructor) – 2014-08-31 09:31:50

+0

在我發佈帖子之前,我通過這個帖子來了,但不幸的是它無法解決我的問題。 – Sisyphus 2014-08-31 09:35:53

+0

遵循其他答案時不起作用? – 2014-08-31 09:36:43

回答

1

該屬性僅在您檢索時才構造(使用GetCustomAttribute函數)。否則,其構造配方(構造函數重載+位置參數+屬性值)僅存儲在程序集元數據中。

就你而言,我會從程序集中檢索所有枚舉類型,並檢查它們是否具有該屬性。類似的東西在你的應用程序的啓動:

var allEnumTypes = Assembly.GetExecutingAssembly() 
          .GetTypes() 
          .Where(t => t.IsEnum); 

foreach(var enumType in allEnumTypes) 
{ 
    var syncAttr = Attribute.GetCustomAttribute(enumType, typeof(EnumSyncAtrribute)) as EnumSyncAtrribute; 
    if (syncAttr != null) 
    { 
     // Possibly do something here, but the constructor was already executed at this point. 
    } 
} 
+0

這是導致Attribute構造函數觸發的唯一方法嗎?當類實例化時,如何自動觸發類屬性? – Sisyphus 2014-08-31 10:08:07

+2

是的,這是唯一的方法。不,他們也不會開火。 – 2014-08-31 10:32:36

+1

因爲它們是屬性。除非有人決定解僱他們,否則他們只是數據。 – 2014-08-31 11:21:46

相關問題