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.

3
  • Inheritance and Polymorphism would go well here. Commented Apr 27, 2016 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. Commented Apr 27, 2016 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. Commented Apr 28, 2016 at 5:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.