Define a default constructor for existing classes in an assembly

Is there a way to define a default constructor for all classes in a given assembly. For example, I have classes like this in the assembly -

public class SomeClass { public SomeClass(int x, int y) { } } 

All of these classes require a default constructor, but I don’t want all these classes to think about a standard constructor, so how do I do this using reflection or something like that? (Maybe TypeBuilder.DefineDefaultConstructor?)

+4
source share
2 answers

All of these classes require a default constructor, but I don’t want all these classes to think of a standard constructor

If classes require a constructor, you must include it. Everything else will be a nightmare in terms of service.

The main problem with the constructor auto-generator is that the default constructor must know about the class in question, since it must correctly initialize the class values. In your example, your default constructor will have to do something to set the internal state, usually created using x and y . There is no way to know what it should be without knowing the class, so the class must define it.

However, there is no direct way to simply add constructors to each type. You could potentially use a tool like Cecil to rewrite the assembly with your changes β€” basically, load the assembly, check each type, add new information and rewrite it. Alternatively, you can use some kind of AOP tool, such as PostSharp , to create constructors at compile time based on some attributes or the like.

I would recommend against these approaches. I believe that it is very important to change the code itself and include constructors, if necessary.

+3
source

You cannot change the compiled class at run time to add a default constructor.

You can do this at compile time using Aspect Oriented Programming. Check out PostSharp .

0
source

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


All Articles