简体   繁体   中英

Types not found in loaded assembly

My project has 2 DLLs, one is Android specific and the other is platform independent. The independent DLL loads the Android assembly and calls the GetTypes method but it is not returning all of the public classes. The Android DLL has 3 classes, 2 are static with static methods only. Only one can be instantiated. The static classes are not returned.

Class1.cs (compile to dll in VS):

using System;
using System.Reflection;

namespace ClassLibrary1
{
    public class Class1
    {
        public void test()
        {
            Assembly asm = Assembly.Load("ClassLibrary2");
            Type T = asm.GetType("ClassLibrary2.Class2");

            T.InvokeMember("Method", BindingFlags.Static |    BindingFlags.InvokeMethod, null, T, null);
        }
    }
}

Class2.cs (Compile to a separate dll in VS):

namespace ClassLibrary2
{
    public static class Class2
    {
        public static void Method()
        {
            return;
        }
    }
}

UnityClass.cs (Assign to a Empty GameObject in Unity 5.x):

using UnityEngine;
using System;

class UnityClass : MonoBehaviour
{
    public void Start()
    {
        var x = new ClassLibrary1.Class1();
        x.test();
    }  
}

Have a look at the following note in the msdn regarding BindingFlags :

You must specify Instance or Static along with Public or NonPublic or no members will be returned.

If you add BindingFlags.Public to your call you should get the member.

Also the 4th parameter target is not required when invoking a static member, you don't have to pass in the type as target, just use null.

As a last note, from personal experience i recommend to get the desired member first by using Type.GetMethod , Type.GetField , ... instead of using InvokeMember . That gives you the possibility to null check the return value to verify that you have found the member you are searching for. That is better for debugging as well as throwing meaningful exceptions during runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM