2009-09-10 6 views
6

私はC#.net(2.0)でシステムを書いています。それは、プラグイン可能なモジュールのアーキテクチャを持っています。ベースモジュールを再構築することなく、アセンブリをシステムに追加することができます。新しいモジュールに接続するために、別のモジュールで静的メソッドを名前で呼び出そうとします。ビルド時に呼び出されるモジュールがどのような方法でも参照されることは望ましくありません。C#は、実行時にビルド時間の参照なしに静的メソッドを呼び出しますか?

私は、.dllファイルのパスから開始してアンマネージコードを書き出していましたが、LoadLibrary()を使用してメモリに.dllを取得し、getProcAddress()を使用して呼び出す関数へのポインタを取得します。どのようにC#/ .NETで同じ結果を達成するのですか?

答えて

16

アセンブリがAssembly.LoadFrom(...)を使用してロードされた後、あなたが名前で型を取得し、任意の静的メソッドを取得することができます:

Type t = Type.GetType(className); 

// get the method 
MethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static); 

Then you call the method: 

method.Invoke(null,null); // assuming it doesn't take parameters 
+2

+ 1、また、 'className'には "MyNamespace.Class1"のような名前空間も含める必要があります。 – icl7126

1

ここのサンプルです:

 string assmSpec = ""; // OS PathName to assembly name... 
     if (!File.Exists(assmSpec)) 
      throw new DataImportException(string.Format(
       "Assembly [{0}] cannot be located.", assmSpec)); 
     // ------------------------------------------- 
     Assembly dA; 
     try { dA = Assembly.LoadFrom(assmSpec); } 
     catch(FileNotFoundException nfX) 
     { throw new DataImportException(string.Format(
      "Assembly [{0}] cannot be located.", assmSpec), 
      nfX); } 
     // ------------------------------------------- 
     // Now here you have to instantiate the class 
     // in the assembly by a string classname 
     IImportData iImp = (IImportData)dA.CreateInstance 
          ([Some string value for class Name]); 
     if (iImp == null) 
      throw new DataImportException(
       string.Format("Unable to instantiate {0} from {1}", 
        dataImporter.ClassName, dataImporter.AssemblyName)); 
     // ------------------------------------------- 
     iImp.Process(); // Here you call method on interface that the class implements 
+0

インスタンスメソッドを呼び出すためのコード。私は静的な方法を求めた。しかし、私はこの断片が最終的に必要になるでしょう。ありがとう。 +1 –

関連する問題