Dynamically building method/property bodies
So I've got this boilerplate code that I want to apply to a bunch of properties of certain classes, that is essentially identical for each one. Rather than have to type th开发者_高级运维is same code out again and again for all of these properties, I was wondering if there was any way I could dynamically build these property methods either post-compile or at runtime, by assigning a C# attribute to the property that includes the slight difference for each method (a string) and then finding these properties by reflection.
I'm aware of PostSharp, but I'm looking for something free or open source.
For example, instead of having to do this:
public string Name {
get { return _member.GetValue( "othername" ); }
set { _member.SetValue( "othername", value ); }
}
...for each property I have, I just want to say this:
[MapTo( "othername" )]
public string Name { get; set; }
Any thoughts?
- You can use Mono.Cecil for dynamic code injection.
- You can make these properties as virtual and generate class that overrides these properties and compile new class to assembly where overridden properties will be defined. Then you should create instance of dynamic generated class and used it as defined class.
You can do something similar using the Unity interception extension.
OK, so it probably merits its own answer. I am aware of the following AOP Frameworks for which you won't have to pay:
- Castle Dynamic Proxy
- Introducing LinFu, Code
Looks like you are looking for an AOP (Aspect Oriented Programming)
like PostSharp
.
It allows you to programatically inject code (just like you mentioned) and is very flexible.
Check out CInject on Codeplex which is an open-source alternative to code injection
精彩评论