mercredi 4 août 2021

Create different instances with Activator.CreateInstance() based on constructors overload [duplicate]

I using Reflection for creating different instances (different names) at runtime, but I've encountered a problem when some classes have a second constructor, how can I treat this? For example:

Case 1:

The class for which I need to create an instance at runtime:

 public class Telegram1
 {
       
        public Telegram1()
        {
        }
        
       // ... some code ...
 }

The creation of the instance at runtime:

string number = 1 // (actually the number is read from a textbox)

Type type = typeof(Telegram);
Assembly assembly = Assembly.GetAssembly(type);
ObjectHandle inst = Activator.CreateInstance(assembly.FullName, $"Telegram{number}");

Until here, everything works great! BUT some classes (I don't know which one) have a second constructor, like the example from below:

Case 2:

public class Telegram2
 {
       
        public Telegram2()
        {
        }

        public Telegram2(byte[] payload) : base(payload)
        {
        }
        
        // ... some code ...
 }

The creation of the instance at runtime for this should be done like this:

string number = 1 // (actually the number is read from a textbox)
byte[] payload = new byte[] {0, 0, 0, 0};
Type type = typeof(Telegram);
Assembly assembly = Assembly.GetAssembly(type);
ObjectHandle inst = Activator.CreateInstance(assembly.FullName, $"Telegram{number}", new object[] { payload });

Also in this case everything works great, but my problem is: how I can know, or find at runtime if the class has two constructors, to use either the first case or the second case?

Edit(a different question): Also, It's a way to check if some classes exists in the assemble, if not just skip the creation of instances? For example Telegram9 doesn't exist, so if the user enters the number 9 in the textbox bind to number property will throw an error, but I want just to avoid the error and skip that part. Basically, If a specific telegram doesn't exist in Assembly don't create an instance for it.





Aucun commentaire:

Enregistrer un commentaire