我想在C#中理解AST.我想知道,Compile()这个例子的确切方法是什么.
// Some code skipped
Expression<Func<string, int, int, string>> data = Expression.Lambda<Func<string, int, int, string>>(
Expression.Call(s, typeof(string).GetMethod(“Substring”, new Type[] { typeof(int), typeof(int) }), a, b),
s, a, b
);
Func<string, int, int, string> fun = data.Compile();
Run Code Online (Sandbox Code Playgroud)
为了防止误解,我理解Expression.Lambda和Expression.Call构建.我感兴趣的是Compile()方法.它以某种方式生成真正的MSIL?我能看到MSIL吗?
考虑这个课程:
/// <summary>
/// Dummy implementation of a parser for the purpose of the test
/// </summary>
class Parser
{
public List<T> ReadList<T>(Func<T> readFunctor)
{
return Enumerable.Range(0, 10).Select(i => readFunctor()).ToList();
}
public int ReadInt32()
{
return 12;
}
public string ReadString()
{
return "string";
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用已编译的lambda表达式树生成以下调用:
Parser parser = new Parser();
List<int> list = parser.ReadList(parser.ReadInt32);
Run Code Online (Sandbox Code Playgroud)
但是,表现并不完全相同......
class Program
{
private const int MAX = 1000000;
static void Main(string[] args)
{
DirectCall();
LambdaCall();
CompiledLambdaCall();
}
static void DirectCall()
{
Parser …Run Code Online (Sandbox Code Playgroud) 有没有办法从C#代码生成汇编代码?我知道C代码可以使用GAS,但有人知道C#是否可行?
我有几行代码
public void CreateMethod<TContract>(Expression<Action<TContract>> method)
{
var innerMethod = Builder.DefineMethod("SomeName",MethodAttributes.Private);
method.CompileToMethod(innerMethod);
//more code
}
Run Code Online (Sandbox Code Playgroud)
但是第二行失败了.我尝试过使用不同版本的DefineMethod,运气不佳.有什么建议?