获取类

时间:2017-02-28 16:38:42

标签: c#

我正在尝试使用自定义属性来生成用户将发布到我的控制台应用程序中的命令列表(字符串),并且将执行相应的方法。我现在卡住了,我的命令列表总是空的。

这是我的属性:

public class ImporterAttribute : Attribute
{
    public string Command { get; set; }
}

这是班级:

public class DataProcessor
{
    public List<ImporterAttribute> Commands { get; set; }

    public DataProcessor()
    {
        //Use reflection to collect commands from attributes
        Commands = GetCommands(typeof(DataProcessor));
    }

    public static List<ImporterAttribute> GetCommands(Type t)
    {
        var commands = new List<ImporterAttribute>();

        MemberInfo[] MyMemberInfo = t.GetMethods();

        foreach (MemberInfo member in MyMemberInfo)
        {
            var att = (ImporterAttribute)Attribute.GetCustomAttribute(member, typeof(ImporterAttribute));

            if (att == null) continue;

            var command = new ImporterAttribute();
            command.Command = att.Command;
            commands.Add(command);
        }

        return commands;
    }

    [Importer(Command = "?")]
    private string Help()
    {
        return "Available commands: " + (from c in Commands select c.Command).Aggregate((a, x) => a + " " + x);
    }

    [Importer(Command = "Q")]
    private void Quit()
    {
        Environment.Exit(0);
    }
}

然后我使用switch语句检查命令列表中的用户输入并运行所请求的方法。所以我的问题是:为什么我的命令列表总是为空?我想我只是误解了the docs中的某些内容。

奖金问题:有没有人有更好/更实用的方法,他们使用/已经用来解决这个问题?

1 个答案:

答案 0 :(得分:3)

您的代码存在的问题是您的方法是私有的。默认情况下,GetMethods仅检索公开方法,因此,如果您将HelpQuit方法签名更改为public,则会获得2个命令。

如果您想将它们保密,可以使用BindingFlags,如下所示:

t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
相关问题