How to add an object creation process in .net

I want to customize the behavior of an object before creating the object. I think maybe add some hooks in the constructor of the objects and make a change there will be a choice. Is there a way to do this in .net? Thank you very much in advance!

EDIT:

Here is an example:

Suppose we have a Kid class that uses the Perform method to get credit in the class.

public class Kid
{
    public void Perform() { ... }
}

And the school gives 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 child to do the same, and I do not want:

  • Modify the Kid class because it is created from a third-party tool and is widely used elsewhere.
  • Use inheritance.
+3
source share
3 answers

. factory, ; new SpecialObject() MyExtendedSpecialObject.Create() .

public static class MyExtendedSpecialObject
{
    public static SpecialObject Create()
    {
        var newObject = new SpecialObject();

        // Do something with newObject

        return newObject;
    }
}
+3

. .., .NET.

public class MyClass
{
    public MyClass()
    {
        // Constructor logic here...
    }

    public MyClass(string name)
    {
         // Overloaded constructor logic here...
    }
}
0

You can use System.Activator to create instances. You can also β€œconnect” to the activator and carry out your checks.

0
source

Source: https://habr.com/ru/post/1754777/


All Articles