我正在使用T4Template和codeDOM使用以下代码创建程序集:
CompilerParameters Params = new CompilerParameters();
Params.GenerateExecutable = true;
Params.ReferencedAssemblies.Add("System.dll");
Params.OutputAssembly = "myfile.exe";
RuntimeTextTemplate1 RTT = new RuntimeTextTemplate1();
string Source = RTT.TransformText();
CompilerResults Create = new CSharpCodeProvider().CompileAssemblyFromSource(Params, Source);
Run Code Online (Sandbox Code Playgroud)
模板看起来像这样(暂时):
<#@ template language="C#" #>
namespace Application
{
class Program
{
static void Main()
{
byte[] buffer = new byte[1024];
//And some code for creating a file with the bytes in the buffer.
}
}
}
Run Code Online (Sandbox Code Playgroud)
在主应用程序中,我有一个字节数组,其中包含某个应用程序的某些字节,这些字节在运行时加载到数组中.
我的问题是:
byte[] buffer = new byte[1024];因此当使用模板中编写的代码创建程序集时,数组应包含字节.就我个人而言,我更喜欢在运行时将数据传递给生成的代码,但如果您确实需要将其嵌入到生成的程序集中,那么您可以执行以下操作:
添加一个类功能块,其中包含字节数组参数作为成员,然后您将能够从运行时模板中设置它并在模板中访问它。像下面这样的东西
<#@ template language="C#" #>
namespace Application
{
class Program
{
static void Main()
{
byte[] buffer = new byte[1024] { <#= BufferValue.Select(b => "0x" + b.ToString("X2")).Aggregate((f, s) => f + ", " + s) #> };
//And some code for creating a file with the bytes in the buffer.
}
}
}
<#+
public byte[] BufferValue { get; set; }
#>
Run Code Online (Sandbox Code Playgroud)
RTT.BufferValue然后在调用模板之前设置为您的数组。