开发者

C# code generation in .NET 4

Does new (>2.0) .NET framework provide any enhancements to code generation?

I u开发者_高级运维sed CodeDom in 2.0 and I wonder if code generation can be simpler.


It depends on what you want to accomplish.

You mentioned using the CodeDom to generate code- if your looking to generate methods on the fly, then you can use LINQ expressions (i cant think of a really good tutorial off of the top of my head but just google for it).

LINQ expressions have the benefit of being easier to write (in my experience), quicker to generate (especially when you write an entire class to encapsulate a single method) and very quick to execute.

The following is a VB.Net snippet of a LINQ expression that generates a function that takes in a ASP.Net control and returns its (protected) ViewState property value:

 'generate a delegate that can access the protected control property "ViewState" 
 '(by using LINQ expressions, we can avoid the performance hit of reflection)
  Dim cntrlParam As ParameterExpression = Expression.Parameter(GetType(Control), "cntrl")
  Dim vsPropertyAcessor As MemberExpression = Expression.Property(cntrlParam, "ViewState")
  dim viewStateAccessor as Func(of Control, StateBag) = Expression.Lambda(vsPropertyAcessor, cntrlParam).Compile()

We can then invoke the generated function like so:

viewStateAccessor (myCntrl)("my_vs_key")

If your looking to do static code generation, then check out the text template feature of VS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜