私はカスタム属性を使用して、ユーザーがコンソールアプリケーションに発行するコマンド(文字列)のリストを生成しようとしており、対応するメソッドが実行されます。私は現在立ち往生しています、私のコマンドリストは常に空です。ここでクラス内のすべてのメソッドの属性リストを取得する
は私の属性です:
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ステートメントを使用します。だから私の質問は:私のコマンドリストは常にnullですか?私はちょうどthe docsの何かを誤解したと思います。
ボーナスに関する質問:この機能に対処するために使用した/使用した方が優れた、より実践的なアプローチを持っていますか?
あなたは[MCVE](単にコンソールアプリ)にあなたの例を書き換えるでした/ペースト/実行/再作成せずにそれを自分で再作成する必要がありますか? –
(しかし、バインディングフラグを持たない 'GetMethods 'で始めるとパブリックメソッドだけが返され、属性を持つパブリックメソッドはありません...) –