CodeDom - can I generate an anonymous methodmethodwi?

N

Niels Ull

Hi!

I'm using .Net 2.0 and C#, and I'm trying to generate code for build time
AOP. But I cannot find out how to generate an anonymous delegate.

E.g. generating code like this:


class MyClassWrapper
{
public static void StaticMethod(int param1, int param2)
{
DbContext.DoInTransaction( delegate { MyClass.StaticMethod(param1,
param2} );
}
}


Background: This is based on having MyClass

class MyClass
{
[TransactionRequired]
public static void StaticMethod(int param1, int param2) {...}
}


But apparently I cannot generate this with the CodeDOM?

My best approach so far is to do a C# roundtrip - e.g.

private CodeExpression GetAnonymousDelegateExpression(CodeStatement statementToWrap)
{
CodeExpression delegateExpression;
CSharpCodeProvider csc = new CSharpCodeProvider();
StringWriter sw = new StringWriter();
csc.GenerateCodeFromStatement(statementToWrap, sw, new CodeGeneratorOptions());
delegateExpression = new CodeSnippetExpression("delegate {" + sw.ToString()
+ "}");
return delegateExpression;
}

but that seems very clunky? Any ideas?
Having to generate my own randomly-named method will be a bit complex since
I have to handle capturing outer variables
 
N

Nicholas Paldino [.NET/C# MVP]

Neils,

Unfortunately, I don't think that the CodeDom namespace has been updated
to accomidate anonymous methods. It also doesn't seem like it's going to be
updated for lambda expressions either. If your snippet works (I haven't
tested it), then I would say that's the way you have to go.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top