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

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

.net - Creating C# Classes at runtime

I have been curious about dynamically create class at runtime in C# and stumbled across this article. http://olondono.blogspot.com/2008/02/creating-code-at-runtime.html I am curious to hear some pros and cons regarding construction of a class at runtime.

Any opinions?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Meta-programming has all the advantages of build-time code-gneneration, but without the additional code step. This is very common in library code, such as ORMs, serializers, some types of AOP, DI/IoC containers, etc.

  • + avoids the need for extra build steps or writing mundane code
  • + such code can handle what actually is the case at runtime, rather than having to handle any uncommon edge-cases or lots of wrappers around wrappers (decorator pattern)
  • + allows codegen in scenarios where the metadata is only known at runtime
  • + runtime IL can have more access to private fields etc, thanks to how DynamicMethod can be associated with a type; fully generated (dll) code would require [InternalsVisibleTo] or similar, which may be impossible
  • - not all systems support runtime code-gen; it is disabled on some server setups, compact framework, iPhone, etc
  • - it is bug ugly to do. Regardless of how you do it, this is not normal code.
  • - it needs a really good understanding of how things actually work under the covers
  • + if forces you to get a really good understanding of how things actually work under the covers

I'm currently re-writing an existing library to use runtime IL generation; it is very rewarding and I'm happy with it; but it is unlike anything I've written before.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...