2012-03-10 79 views
0

我想創建一個自定義屬性,允許我的每個自定義控件庫中的方法在運行時初始化。我設法得到這個使用反射如下工作:C++/CLI屬性

InitOnload::initialise() 
{ 
    // get a list of types which are marked with the InitOnLoad attribute 
    array<System::Reflection::Assembly^>^ assemblies = System::AppDomain::CurrentDomain->GetAssemblies(); 

    for each(System::Reflection::Assembly^ assembly in assemblies) 
    { 
     try 
     { 
       System::Type^ type = System::Type::GetType("INITONLOAD.InitOnload"); 

       array<Object^>^ attributes = assembly->GetCustomAttributes(type, false); 

      if(attributes->Length > 0) 
      { 
       auto field = 
       type->GetFields(
       System::Reflection::BindingFlags::Static | 
       System::Reflection::BindingFlags::Public | 
       System::Reflection::BindingFlags::NonPublic); 
      } 
      } 
     catch (...) 
     { 
     } 
     } 
} 

foo2的被啓動時初始化,但只有當它在相同的命名空間如上InitOnload定義。

[assembly: InitOnload()]; 
public ref class foo2 : public System::Attribute 
{ 
public: 
    foo2() 
    { 
    }; 

}; 

如果我嘗試在不同的自定義控制庫不initilaise foo2的下方initilaise方法不initilalise:

[assembly: INITONLOAD::InitOnload()]; 
public ref class foo : public System::Attribute 
{ 
public: 
    foo() 
    { 
    }; 

}; 

任何想法?

+2

有人將不得不首先加載程序集。 – 2012-03-10 17:53:26

回答

1

System::AppDomain::CurrentDomain->GetAssemblies()只列出已加載的程序集。因爲.NET沒有延遲加載,所以它包含你引用的所有程序集。

我建議您安裝AppDomain::AssemblyLoad事件的處理程序,並在加載它們時處理將來程序集中的類型。