dimanche 21 mars 2021

C# how use reflection to load dependency assembly?

I am using reflection to load Assembly1.dll and print out all its methods:

            Assembly assembly1 = Assembly.LoadFile("c:\temp\Assembly1.dll");

            foreach (Type type in assembly1.GetExportedTypes())
            {
                Console.WriteLine();
                Console.WriteLine(type.ToString());

                foreach (MethodInfo methodInfo in type.GetMethods())
                {
                    Console.Write($"    {(methodInfo.IsStatic ? "static" : "")} {methodInfo.ReturnType} {methodInfo.Name} (");
                    ParameterInfo[] aParams = methodInfo.GetParameters();

                    for (int i = 0; i < aParams.Length; i++)
                    {
                        ParameterInfo param = aParams[i];

                        if (i > 0)
                            Console.Write(", ");

                        Console.Write($"{ (param.ParameterType.IsByRef && param.IsOut ? "out" : "") } { (param.ParameterType.IsByRef && !param.IsOut ? "ref" : "") } {param.Name}");
                    }
                }
            }

When the last "Consol.Write" runs, it threw the following exception:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Assembly2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.'

I know why, because some of the methods in Assembly1.dll has some parameters, and the types of these parameters are defined in Assembly2.dll.

So, how do I solve this problem? I mean, how do I load both assemblies?





Aucun commentaire:

Enregistrer un commentaire