Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
suppose I have many classes developed by a different programmer, so that I cannot change his code. All these classes has the same constructor and they are all derived from the same base class.
I would like to modified the base constructor of this classes (but I can't). Is there a way to reuse this classes without changing them directly, but using a different constructor. An example:

class A
      {
          public A(List<double> a) { }
      }

      class A1: A
      {
          public A1(List<double> a):base(a) { }
      }

      class A2:A
      {
          public A2(List<double> a):base(a) { }
      }


I can't change classes A, A1, A2. I want to use them allowing to accept double[] instead of List<double> as constructor. I dont want to wrap each time. Is there a design solution?
Posted
Updated 5-Sep-12 23:21pm
v2
Comments
Richard MacCutchan 6-Sep-12 6:08am    
If you cannot change them then you will need to create your own classes which inherit from these ones. The question is, why bother just so you can use a raw array rather than a list?

1 solution

You could create a static class with a generic method to create the objects. It assumes that all the constructors are the same, which in this case won't be a problem.

C#
//using System.Reflection;

    public static class Wrapper
    {
        // where clause ensures that it only works for the A class and it's derived classes
        public static T CreateA<T>(double[] a) where T : TheOriginalClasses.A 
        {
            // Get the cconstructor
            Type[] types = new Type[1];
            types[0] = typeof(List<double>); 
            ConstructorInfo constructorInfo = typeof(T).GetConstructor(types);

            // Invoke the constructor
            object[] objects = new object[1];
            objects[0] = a.ToList(); 
            T value = constructorInfo.Invoke(objects) as T;

            return value;
        }
    }


You can call this which the following code:

C#
double[] a = new double[3] { 0.5, 1.1, 2.5 };

var testA = Wrapper.CreateA<TheOriginalClasses.A>(a);
var testA1 = Wrapper.CreateA<TheOriginalClasses.A1>(a);
var testA2 = Wrapper.CreateA<TheOriginalClasses.A2>(a);

Console.WriteLine(testA.GetType().ToString());
Console.WriteLine(testA1.GetType().ToString());
Console.WriteLine(testA2.GetType().ToString());


I'm not sure if this code will win a code beauty contest, but it will give you a generic wrapper. A disadvantage might be performance loss due to using Reflection.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900