的字符串說你要解釋的一樣AABBCDEEFF命令參數的刺痛......和想法是每個字符代表,你必須採取對類的一些行動的命令時,醜陋的解決方案是寫一個大開關的情況下,但我不想用這個,任何人都可以建議一個更優雅的解決方案?解釋命令
Q
解釋命令
1
A
回答
0
對於C#,在更復雜的情況下的解決方案可以實現和接口,或添加屬性和使用反射來調用命令或方法。
OK,作爲一個例子,我創建了一些C#代碼
public class ExecuteSequence
{
Dictionary<string, Type> classes = new Dictionary<string, Type>();
public void LoadClasses()
{
classes.Clear();
//load all classes with attribute
//this can be done at startup once, or on requested refresh
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (Type type in assembly.GetTypes())
foreach (object attribute in type.GetCustomAttributes(typeof(MethodAttribute), true))
if (attribute.GetType() == typeof(MethodAttribute))
classes.Add(((MethodAttribute)attribute).MethodName, type);
}
public string Execute(string sequence)
{
string retVal = "";
foreach (char c in sequence)
if (classes.ContainsKey(c.ToString()))
{
IMethod method = (IMethod)Activator.CreateInstance(classes[c.ToString()]);
retVal += method.Execute();
}
return retVal;
}
}
public class MethodAttribute : Attribute
{
private readonly string m_MethodName;
public MethodAttribute(string methodName)
{
m_MethodName = methodName;
}
public string MethodName
{
get { return m_MethodName; }
}
}
public interface IMethod
{
string Execute();
}
[Method("A")]
public class MethodA : IMethod
{
public string Execute()
{
return "FOO";
}
}
[Method("B")]
public class MethodB : IMethod
{
public string Execute()
{
return "BAR";
}
}
您可以限制掃描初始組件列表中,但如前所述,這應該只在啓動時加載。
希望這會有所幫助。
1
那麼我的建議是開關,因爲編譯器會優化它。有多少潛在角色會發生?
2
讓一切儘可能簡單。留在開關。
4
創建地圖等的方法:map<char, func_ptr>
,然後用你的 「行動」 填補它:
act_map['A'] = &my_class::func_a
....
和
for each c in str
arc_map[c]()
真正的實現取決於你的語言。
但是,如果你有多達5-10行動比只使用開關。
相關問題
- 1. 命令解釋器/解釋
- 2. 命令解釋
- 3. 解釋awk命令
- 4. 解釋「:>」命令
- 5. Unix命令解釋
- 6. 在mysql中解釋命令
- 7. 解釋find -mtime命令
- 8. Marie命令行解釋器
- 9. bash命令的解釋
- 10. 解釋使用命令
- 11. 命令行解釋器
- 12. bash命令的解釋
- 13. 請解釋!SyncBlk windbg命令
- 14. 批處理命令解釋
- 15. grep命令解釋需要
- 16. 解釋bash命令$ {PATH}:
- 17. fvctl命令的解釋?
- 18. Hadoop的命令行解釋
- 19. 解析JSON像在命令行解釋
- 20. 每行有多個命令的命令行解釋器
- 21. Mongo DB shell,remove命令不返回遊標來解釋(命令)?
- 22. shell vs命令解釋器與命令行?
- 23. 命令參數被解釋爲命令文件名
- 24. 打開另一個命令行解釋器並輸入命令
- 25. PHP命令行 - 鏈的解釋
- 26. vim的解釋:%w!pbcopy命令
- 27. 無法解釋的聲明命令JDBC
- 28. c中的命令行解釋器
- 29. Lucene QueryParser將'AND OR'解釋爲命令?
- 30. numpy的陣列更新命令解釋
@all提示開關,目前我使用開關,但在我的情況有一個維護問題的命令列表我要支持可能會改變,或者說他們的行爲可能會改變 – redzedi