简体   繁体   中英

Get all methods that have an attribute

I have a project that I am loading in an Assembly. That assembly has a reference to NUnit.

My project also has a reference for NUnit to find all methods that contain an attribute. However, When I query the methods, it seems like that the two NUnit assemblies are different and thus doesn't successfully get the methods.

Is there a way to just not compare assemblies somehow?

    private static IEnumerable<MethodInfo> GetTestMethods()
    {
        var alc = new TestAssemblyLoadContext("SomeDll.dll");

        Assembly assembly = alc.LoadFromAssemblyPath("SomeDll.dll");

        // This works but returns all methods
        var good = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods());

        // This doesn't work since TestAttribute is from another assembly (seems like it compares all TestAttributes that have this projects Assembly but the actual assembly in the DLL is not the same)
        var bad = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0 || m.GetCustomAttributes(typeof(TestCaseAttribute), false).Length > 0);

        alc.Unload();
        return bad;
    }

I won't talk of the overall architecture you seem to be using, but for your specific problem you can just use the m.GetCustomAttributes(false) overload, and then test the attribute's name as a string rather than a type if needed.

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