Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to understand AST in C#. I wonder, what exactly Compile() method from this example does.

// 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(); 

To prevent misunderstandings, I understand the Expression.Lambda and Expression.Call constructs. What interests me is the Compile() method. Does it somehow produce real MSIL? Can I see the MSIL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
289 views
Welcome To Ask or Share your Answers For Others

1 Answer

What interests me is the Compile() method. Does it somehow produce real MSIL?

Yes. The Compile method runs a visitor over the lambda body block and generates IL dynamically for each subexpression.

If you're interested in learning how to spit IL yourself, see this "Hello World" example of how to use Lightweight Codegen. (I note that if you are in the unfortunate position of having to use Lightweight Codegen in a partially trusted appdomain then things can get a bit weird in a world with Restricted Skip Visibility; see Shawn Farkas's article on the subject if that interests you.)

Can I see the MSIL?

Yes, but you need a special "visualizer". The visualizer I used to debug Compile() while I was implementing my portions of it can be downloaded here:

http://blogs.msdn.com/b/haibo_luo/archive/2005/10/25/484861.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...