0

Usually I do this:

MyCustomDocument1 bla1=new MyCustomDocument1()
temp.GeneratesSingleDocument<MyCustomDocument1>(bla1);

MyCustomDocument2 bla2=new MyCustomDocument2()
temp.GeneratesSingleDocument<MyCustomDocument2>(bla2);

MyCustomDocument3 bla3=new MyCustomDocument3()
temp.GeneratesSingleDocument<MyCustomDocument3>(bla3);

But this time I have a list(with all the classes from above):

List<object> allObjects = new List<object>();

It is filled like this(all objects I need):

allObjects.Add(new MyCustomDocument1());
allObjects.Add(new MyCustomDocument2());
allObjects.Add(new MyCustomDocument3());
allObjects.Add(new MyCustomDocument4());
allObjects.Add(new ...());

Now I want to call my generic method with my previous filled list ``:

foreach (var item in allObjects)
{
    try
    {
         //instead of manually calling:
        //temp.GeneratesSingleDocument<MyCustomDocument1>(bla1);
        //do it generic
        temp.GeneratesSingleDocument<typeof(item)>(item);

    }
    catch (Exception e)
    {

        Debug.WriteLine(e.Message);
    }

}

This does not work:

temp.GeneratesSingleDocument<typeof(item)>(item);

The overall aim is to make some automation, otherwise I have to write a lot of code.

I think this is different from this post.

Thank you.

Community
  • 1
  • 1
kkkk00999
  • 179
  • 2
  • 13
  • Inheritance and Polymorphism would go well here. – Master Apr 27 '16 at 16:24
  • 1
    What does `GenerateSingleDocument` look like? Why is it even generic if you can pass any old object into it? Looks like you need to define an interface for what's common across your classes and have GenerateSingleDocument accept that interface. – Ian Mercer Apr 27 '16 at 16:37
  • @Ian Mercer you are right I can pass any object of to it(but `GeneratesSingleDocument` will match only a few of them, inside that method there is a wswitch case checking for its type and than doing its work), actually `GeneratesSingleDocument` its an interface method :) .But I want to generate documents for certain classes, it is just for testing. – kkkk00999 Apr 28 '16 at 05:02

1 Answers1

1

You can use reflection. Try this:

var genericMethod = temp.GetType().GetMethod("GeneratesSingleDocument").MakeGenericMethod(typeof(item));
genericMethod.Invoke(temp, new object[] { item });

Be aware that reflection comes with performance and code maintenance issues--here's a good link for you to read. Best of luck.

Community
  • 1
  • 1
John Riehl
  • 1,270
  • 1
  • 11
  • 22