我从 excel 中读取数据并确定要执行的事件。
事件都是我自己创建的类(登录和注销)
如果我读取的值 = 1 ,则执行登录
如果我读取的值 = 2 ,则执行注销
我使用 switch 但我的老板说我必须在 Java 中使用 hashmap 之类的东西。
在 Java 中,我可以编写如下代码:
table.Add("one", login.class);
那么如何使用 c# 将类添加到哈希表中?
以及如何读取值并调用哈希表中的类方法?
您可以使用委托。例如,如果您有以下方法:
public void Login() {
// ...
}
public void Logout() {
// ...
}
你可以使用这个Dictionary
:
Dictionary<string, Action> actions = new Dictionary<string, Action>() {
{"Login", Login},
{"Logout", Logout}
};
然后这样称呼它:
actions[myAction]();
当然,您需要确保密钥存在。您可以以与调用常规方法几乎相同的方式调用委托。如果它们有参数或返回值,只需使用适当的Action<T1, T2...>
or Func<T1, T2... TOut>
。
以下代码允许您DoSomething
在对象中实现一个方法,该方法可从 Dictionary 索引中调用:
public interface ICallable
{
void Execute();
}
public class Login : ICallable
{
// Implement ICallable.Execute method
public void Execute()
{
// Do something related to Login.
}
}
public class Logout : ICallable
{
// Implement ICallable.Execute method
public void Execute()
{
// Do something related to Logout
}
}
public class AD
{
Dictionary<string, ICallable> Actions = new Dictionary<int, ICallable>
{
{ "Login", new Login() }
{ "Logout", new Logout() }
}
public void Do(string command)
{
Actions[command].Execute();
}
}
示例用法
AD.Do("Login"); // Calls `Execute()` method in `Login` instance.