Question

I have two very simple methods, one of which I can invoke and the other give me not found exception, here are the methods:

class SimClass
    {
        public int GeneralMethod1(int a)
        {
            return a;
        }

        public int GeneralMethod2(Input input)
        {
            return input.Numberi;
        }

    }
    class Input
    {
        public int Numberi { get; set; }
    }

I simply can invoke "GeneralMethod1":

        Assembly assembly = Assembly.LoadFrom("C:\\Amir\\SimFIle.dll");
        Type type = assembly.GetType("SimFIle.SimClass");
        object instanceOfMyType = Activator.CreateInstance(type);

        object[] Args1 = new object[1]; Args1[0] = -1;
        object result = type.InvokeMember("GeneralMethod1",
              BindingFlags.Default | BindingFlags.InvokeMethod,
                   null,
                   instanceOfMyType,
                   Args1);

but have problem in invoking "GeneralMethod2":

    Input input = new Input { Numberi = -5};
    object[] Args2 = new object[1]; Args2[0] = input;
    object output = type.InvokeMember("GeneralMethod2",
          BindingFlags.Default | BindingFlags.InvokeMethod,
               null,
               instanceOfMyType,
               Args2);

would you please advise what is my mistake?

Was it helpful?

Solution

I suspect the problem is that you've got a different Input class. You're loading SimFile.dll dynamically, but creating an instance of Input statically. That means the Input class you're creating isn't the same as the one in the assembly you're invoking the method in.

If you already have a reference to SimFile.dll in your code, you shouldn't load it explicitly - that's just going to confuse things. If you don't have a reference to SimFile.dll in your project, then presumably you're creating an instance of a completely different Input type.

Either way, you should be able to fix the problem by using the Input class within the dynamically-loaded assembly:

Type inputType = assembly.GetType("Input")
object input = Activator.CreateInstance(inputType);
inputType.GetProperty("Numberi").SetValue(input, -5);

// Rest of code as before
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top