Stream
を使用して DLL を取得できますがAssembly.GetManifestResourceStream
、それを使用して何かを行うには、メモリにロードして を呼び出すか、ファイル システムに展開する必要があります(Assembly.Load
その後、または を呼び出す必要があります。実際にはすでに依存関係があります)。Assembly.Load
Assembly.LoadFile
Assembly.Load
アセンブリをロードした後、リフレクションを使用してクラスのインスタンスを作成したり、メソッドを呼び出したりする必要があります。これはすべて非常に面倒です。特に、 (または同様のメソッド)のさまざまなオーバーロードを呼び出す状況を思い出せません。. Jeff Richter の「CLR via C#」という本は、手元に置いておくと便利なリソースです。
なぜこれを行う必要があるのか について、さらに情報を提供していただけますか?私はさまざまなことにマニフェスト リソースを使用しましたが、コードを含めることはありません...実行可能ファイルと一緒に出荷できない理由はありますか?
エラーチェックなしではありますが、完全な例を次に示します。
// DemoLib.cs - we'll build this into a DLL and embed it
using System;
namespace DemoLib
{
public class Demo
{
private readonly string name;
public Demo(string name)
{
this.name = name;
}
public void SayHello()
{
Console.WriteLine("Hello, my name is {0}", name);
}
}
}
// DemoExe.cs - we'll build this as the executable
using System;
using System.Reflection;
using System.IO;
public class DemoExe
{
static void Main()
{
byte[] data;
using (Stream stream = typeof(DemoExe).Assembly
.GetManifestResourceStream("DemoLib.dll"))
{
data = ReadFully(stream);
}
// Load the assembly
Assembly asm = Assembly.Load(data);
// Find the type within the assembly
Type type = asm.GetType("DemoLib.Demo");
// Find and invoke the relevant constructor
ConstructorInfo ctor = type.GetConstructor(new Type[]{typeof(string)});
object instance = ctor.Invoke(new object[] { "Jon" });
// Find and invoke the relevant method
MethodInfo method = type.GetMethod("SayHello");
method.Invoke(instance, null);
}
static byte[] ReadFully(Stream stream)
{
byte[] buffer = new byte[8192];
using (MemoryStream ms = new MemoryStream())
{
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
return ms.ToArray();
}
}
}
コードのビルド:
> csc /target:library DemoLib.cs
> csc DemoExe.cs /resource:DemoLib.dll