我試圖使用自定義屬性來生成用戶將發佈到我的控制檯應用程序中的命令(字符串)的列表,並執行相應的方法。我目前卡住了,我的命令列表總是空的。獲取類中的所有方法的屬性列表
這裏是我的屬性:
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。
獎金問題:有沒有人有一個更好/更實際的方法,他們使用/已經用來解決這個功能?
你能改寫你的例子爲[MCVE(只是一個控制檯應用程序),以便我們可以複製/粘貼/編譯/運行/重現,而不必自行重做它? –
(但是,以'GetMethods'開始而沒有綁定標誌只會返回公共方法,並且您沒有任何具有屬性的公共方法...) –