在c#中使用自定义属性获取所有方法都找不到方法

问题描述 投票:1回答:1

因此,我创建了此函数来获取具有自定义属性ExecuteFromConsole的所有方法

    [ExecuteFromConsole("test", "help")]
    static void Test(string[] args)
    {
        Debug.Log("Test Ran");
    }

    public void AddAttributeCommands()
    {
        //get all methods with the execute attribute
        var methods = AppDomain.CurrentDomain.GetAssemblies()
                               .SelectMany(x => x.GetTypes())
                               .Where(x => x.IsClass)
                               .SelectMany(x => x.GetMethods())
                               .Where(x => x.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).FirstOrDefault() != null);

        //adds them to commands
        foreach (var method in methods) 
        {
            Debug.Log("Found attribute");
            ExecuteFromConsoleAttribute attribute = (ExecuteFromConsoleAttribute)method.GetCustomAttributes(typeof(ExecuteFromConsoleAttribute), false).First();
            if(!method.IsStatic)
            {
                Debug.LogError("ExecuteFromConsoleAttribute must be used on static functions only");
                continue;
            }
            CommandFunc func = (CommandFunc)Delegate.CreateDelegate(typeof(CommandFunc), method);
            AddCommand(attribute.command, func, attribute.help);
        }
    }

这在我最初进行测试时效果很好,但是现在它永远不会进入foreach循环,并且Debug.log("found attribute")表示它找不到带有属性的明显在其正上方的方法。AFAIK我没有修改任何会影响到此的内容。

有人对为什么它不起作用或我是否正在做错所有事情有见解,而我应该有一种更好的方法来做呢?

如果影响任何项目,则该项目将是统一的

c# linq unity3d reflection custom-attributes
1个回答
0
投票

GetMethods的默认值为“任何公共”,但是您的方法是非方法的。尝试将BindingFlags.NonPublic | BindingFlags.Static添加到GetMethods调用中,以提供更多提示。

© www.soinside.com 2019 - 2024. All rights reserved.