2017-02-28 43 views
3

我試圖使用自定義屬性來生成用戶將發佈到我的控制檯應用程序中的命令(字符串)的列表,並執行相應的方法。我目前卡住了,我的命令列表總是空的。獲取類中的所有方法的屬性列表

這裏是我的屬性:

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

獎金問題:有沒有人有一個更好/更實際的方法,他們使用/已經用來解決這個功能?

+0

你能改寫你的例子爲[MCVE(只是一個控制檯應用程序),以便我們可以複製/粘貼/編譯/運行/重現,而不必自行重做它? –

+0

(但是,以'GetMethods'開始而沒有綁定標誌只會返回公共方法,並且您沒有任何具有屬性的公共方法...) –

回答

3

您的代碼存在的問題是您的方法是私人的。 GetMethods默認只檢索公共方法,所以如果您將HelpQuit方法簽名更改爲public,您將得到2個命令。

如果你想保持他們私人的,你可以使用BindingFlags這樣的:

t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance); 
+0

是的,它解決了它的問題。雖然我不介意在這個特定場景中讓它們公開,但有沒有一種方法可以與'privates'一起使用? – Halter

+1

查看我的更新回答@Halter – Pikoh

相關問題