jeudi 25 juin 2015

Prevent reflectled method from calling other reflected methods c#

It is possible for a class instance to invoke a reflected method, but not have it call one of its other methods, and also without breaking the method or causing an exception.

This is the idea behind my code:

namespace test
{
    class main
    {
        public static int Main(string [] args)
        {
            //This gives my the type of class I want since it is private. (this does work)
            Type classTypeIWant = typeof(otherNamespace.someClassInThatNameSpace).Assembly.GetTypes()
                            .FirstOrDefault(t => t.Name == "ClassIWant");

            //This creates an instance of the class I want using the default constructor
            object classInstanceIWant = Activator.CreateInstance(classTypeIWant);

            //Invoke the method
            int resultINeed = classTypeIWant.GetMethod("MethodIWant")
                    .Invoke(classInstanceIWant, null));
        }
    }
}

namespace otherNamespace
{
    public class someClassInThatNameSpace{}

    private class classIWant
    {
        public classIWant
        {
            //stuff happens
        }

        public void BadMethod(int ruinLife)
        {
            //do stuff
            //do stuff that will not work in my context
            //throw exception
        }

        public int MethodIWant()
        {
            //this is the value I want to grab
            int valueIWant = 10;

            //but this method faults because of things I cannot change (I really cannot change this)
            BadMethod(valueIWant);

            //it will not make it here because of BadMethod
            return valueIWant;
        }
    }
}

If I could somehow prevent BadMethod from being called, or maybe trap the method call and return some fake value that would fix everything.

I have ran through the debugger and the problem has to do with a reference in BadMethod that cannot be resolved because of what BadMethod actually does. There is no way possible for me to prevent BadMethod from faulting, so please don't suggest it.





Aucun commentaire:

Enregistrer un commentaire