你可以使用你的代码创建代码,然后将其保存到临时文本文件中,然后再使用它。这样做会很慢,因为它涉及使用硬盘驱动器。我建议研究一下
reflection。
编辑:我在我的书中找到了一个完美的例子,在这里(它相当冗长,但如果你将它复制到VS中,它会更有意义)。
namespace Programming_CSharp
{
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
public class MyMath
{
public int DoSumLooping(int initialVal)
{
int result = 0;
for(int i = 1;i <=initialVal;i++)
{
result += i;
}
return result;
}
}
public interface IComputer
{
int ComputeSum( );
}
public class ReflectionTest
{
private Assembly EmitAssembly(int theValue)
{
AssemblyName assemblyName =
new AssemblyName( );
assemblyName.Name = "DoSumAssembly";
AssemblyBuilder newAssembly =
Thread.GetDomain( ).DefineDynamicAssembly(
assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder newModule =
newAssembly.DefineDynamicModule("Sum");
TypeBuilder myType =
newModule.DefineType(
"BruteForceSums", TypeAttributes.Public);
myType.AddInterfaceImplementation(
typeof(IComputer));
Type[] paramTypes = new Type[0];
Type returnType = typeof(int);
MethodBuilder simpleMethod =
myType.DefineMethod(
"ComputeSum",
MethodAttributes.Public |
MethodAttributes.Virtual,
returnType,
paramTypes);
ILGenerator generator =
simpleMethod.GetILGenerator( );
generator.Emit(OpCodes.Ldc_I4, 0);
for (int i = 1; i <= theValue;i++)
{
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Add);
}
generator.Emit(OpCodes.Ret);
MethodInfo computeSumInfo =
typeof(IComputer).GetMethod("ComputeSum");
myType.DefineMethodOverride(simpleMethod, computeSumInfo);
myType.CreateType( );
return newAssembly;
}
public double DoSum(int theValue)
{
if (theComputer == null)
{
GenerateCode(theValue);
}
return (theComputer.ComputeSum( ));
}
public void GenerateCode(int theValue)
{
Assembly theAssembly = EmitAssembly(theValue);
theComputer = (IComputer)
theAssembly.CreateInstance("BruteForceSums");
}
IComputer theComputer = null;
}
public class TestDriver
{
public static void Main( )
{
const int val = 2000;
const int iterations = 1000000;
double result = 0;
MyMath m = new MyMath( );
DateTime startTime = DateTime.Now;
for (int i = 0;i < iterations;i++)
result = m.DoSumLooping(val);
}
TimeSpan elapsed =
DateTime.Now - startTime;
Console.WriteLine(
"Sum of ({0}) = {1}",val, result);
Console.WriteLine(
"Looping. Elapsed milliseconds: " +
elapsed.TotalMilliseconds +
" for {0} iterations", iterations);
ReflectionTest t = new ReflectionTest( );
startTime = DateTime.Now;
for (int i = 0;i < iterations;i++)
{
result = t.DoSum(val);
}
elapsed = DateTime.Now - startTime;
Console.WriteLine(
"Sum of ({0}) = {1}",val, result);
Console.WriteLine(
"Brute Force. Elapsed milliseconds: " +
elapsed.TotalMilliseconds +
" for {0} iterations", iterations);
}
}
}
输出:
2000的和=2001000
循环。已过去的毫秒数:
1000000次迭代用时11468.75毫秒
2000的和=2001000
暴力枚举法。已过去的毫秒数:
1000000次迭代用时406.25毫秒
这里是整个章节的链接,如果您想了解更多信息。