如何解决如何使用CSharpCodeProvider传递变量?
我需要用我的应用程序创建一个EXE文件,我可以通过操纵字符串格式来传递字符串,但是我不能传递我需要的其他变量,例如:byte数组,如果有帮助,这是我的代码:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Windows;
namespace ACompiler.CompWorker
{
class CompilerWorker
{
public static byte[] testarray = SomeClass.someArray;
public static string Key = "Testkey12";
public static void Compile()
{
CSharpCodeProvider CompileProvider = new CSharpCodeProvider();
CompilerParameters CompileProviderParameters = new CompilerParameters(new[] { "mscorlib.dll","System.Core.dll" },AppDomain.CurrentDomain.BaseDirectory + "Compiled.exe",true);
CompileProviderParameters.GenerateExecutable = true;
string test= @"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + testarray + @";
string Key = """ + Key + @""";
Console.WriteLine(""Key: "" + EKey);
Console.WriteLine(Content);
Console.ReadLine();
}
}
}
";
var Result = CompileProvider.CompileAssemblyFromSource(CompileProviderParameters,test);
}
}
}
基本上,我想将“ testarray”移到已编译的应用程序中,希望有人能指出正确的方向!
解决方法
诀窍是将数据“序列化”回编译器可以编译的代码。试试这个:
var arrayCode = "new byte[] { " + string.Join(",",testarray) + " }";
string test = @"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + arrayCode + @";
string Key = """ + Key + @""";
Console.WriteLine(""Key: "" + EKey);
foreach(byte b in Content)
{
Console.WriteLine(b.ToString());
}
Console.ReadLine();
}
}
}
";
请记住,您不能对字节数组对象执行Console.WriteLine
并将其吐出每个项目。您将不得不遍历项目以将其打印出来。我更新了您的代码以正确执行此操作。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。