how to add hook in object creation process in .net
I want to customize a object's behavior before the object is created. I think maybe add some hooks in the object constructor and do the change there would be a choice. Is there any way to do so in .net?开发者_如何学Python Thanks a lot in advance!
EDIT:
Here is a example:
Assume we have a class Kid which use Perform method to get credit in the class.
public class Kid
{
public void Perform() { ... }
}
And the School conduct to lectures:
public class School
{
public void Chemistry() {
// The school have a good chemistry teacher, so every kid study well
// Kid.Perform() is modified to reflect that
Kid tom = new Kid();
tom.Perform();
}
public void Biology() {
//This class is boring, everyone will nap in 5~10 min
// Kid.Perform() use a random number to simulate how
//long this kid can hold it.
Kid tom = new Kid(); tom.Perform();
Kid jerry = new Kid(); jerry.Perform();
}
}
We want every kid perform in the same way and I do not want:
- Change class Kid because it is generated from a 3rd party tool and widely used somewhere else.
- Use inheritance.
In your case you would have to add your logic after calling the constructor. You could write a factory method which does this; replacing new SpecialObject()
with MyExtendedSpecialObject.Create()
shouldn't be too difficult.
public static class MyExtendedSpecialObject
{
public static SpecialObject Create()
{
var newObject = new SpecialObject();
// Do something with newObject
return newObject;
}
}
You would simply add logic to the object's constructor. If you are referring to the process of hooking into the allocation of memory etc then that's not available in .NET.
public class MyClass
{
public MyClass()
{
// Constructor logic here...
}
public MyClass(string name)
{
// Overloaded constructor logic here...
}
}
You can use System.Activator to create the instances. You can also 'hook' into the activator and perform your checks.
精彩评论