vendredi 2 juillet 2021

Assembly Invoking using ConstructorInfo with Reflection [duplicate]

I've looked through the other posts and have not found anything that specifically hits on this issue, so here we go...

I have an external DLL class...

namespace Utility
{
    //o--------------------------------o
    //| string style Enumerator class  |
    //o--------------------------------o
    public class StringEnumerator : IEnumerable<string>
    {
        protected List<string> _elements;

        //our constructor
        public StringEnumerator(string[] array)
        {
            this._elements = new List<string>(array);
        }

        IEnumerator<string> IEnumerable<string>.GetEnumerator()
        {
            return this._elements.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this._elements.GetEnumerator();
        }
    }
}

In my testing application I can get the constructor but I can't invoke it...

            Type tmpType2 = localCore.GetType("Utility.StringEnumerator", false, true);
            object ot2a = Activator.CreateInstance(tmpType2, null);
            // Prove that we an object.
            DisplayBuffer($"A {ot2a.GetType().Name} object has been created");
            foreach (MethodInfo mi in tmpType2.GetMethods())
            {
                DisplayBuffer($"  Utility.StringEnumerator.MethodInfo.Name: {mi.Name}");
            }
            Type[] conTypes = { typeof(string[]) };
            // Get a reference to the correct constructor.
            ConstructorInfo ci2 = tmpType2.GetConstructor(conTypes);
            DisplayBuffer($"Utility.StringEnumerator.ConstructorInfo.Name: {ci2.Name}");
            
            // Prepare the parameters.
            object[] args4 = { "Help", "me", "please" };

            // Invoke the constructor and assign the result to a variable. 
            object o4 = ci2.Invoke(args4); //<-- This causes an error
            DisplayBuffer($"Invoked: {o4}");

The error I get is: System.Reflection.TargetParameterCountException: 'Parameter count mismatch.'

If I try this...

object o4 = ci2.Invoke(new object[] { "test string to pass" });

I get the error: System.ArgumentException: 'Object of type 'System.String' cannot be converted to type 'System.String[]'.'





Aucun commentaire:

Enregistrer un commentaire