.NET程序集在运行时初始化

时间:2012-02-27 12:01:53

标签: c++ reflection assemblies

在运行时,我需要能够让我加载的C ++程序集用顶级应用程序注册它们的版本信息。我想的是:

     array<System::Reflection::Assembly^>^ assemblies = System::AppDomain::CurrentDomain->GetAssemblies();

     for each(System::Reflection::Assembly^ assembly in assemblies)
     {}

但是如何确定哪些是我的程序集,哪些是系统程序集。有没有办法在我的类中添加一些静态方法,这段代码可以调用?

这是我实际使用的代码,我试图获取Foo类的属性,以便我可以调用静态方法来请求它自己注册。

public ref class Foo
{
public:

  Foo()
  {
  };

private:

};

public ref class InitOnLoad : System::Attribute 
{ 
public:

  InitOnLoad()
  {
     Foo ^foo = gcnew Foo();
     System::Type^ thisType = foo->GetType();

     // 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("UtilsDotNet.Foo");

           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 (...)
        {
        }
     }
  }
};

1 个答案:

答案 0 :(得分:1)

我会在程序集中添加自定义属性。在继续版本号注册之前,您可以测试每个程序集的属性。

我的语法可能有误,但是......

System::Type^ type = System::Type::GetType("UtilsDotNet.Foo");
array<Object^>^ attributes = assembly->GetCustomAttributes(type, false);

应该是

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

我不确定使用属性标记程序集的C ++方法,但C#方法是将此行放在Assembly.cs文件中(在Properties文件夹下)

[assembly:  InitOnLoad()]

此外,您不应该拥有在属性的构造函数中枚举程序集的代码。如果这样做,则每次找到其中一个属性时都会运行此代码。我将该代码放在一个单独的方法中,也许是属性上的静态方法。

最后,请记住,如果您使用的是后期绑定程序集,则还需要侦听AssemblyLoad事件。