1

我从 excel 中读取数据并确定要执行的事件。

事件都是我自己创建的类(登录和注销)

如果我读取的值 = 1 ,则执行登录

如果我读取的值 = 2 ,则执行注销

我使用 switch 但我的老板说我必须在 Java 中使用 hashmap 之类的东西。

在 Java 中,我可以编写如下代码:

table.Add("one", login.class);

那么如何使用 c# 将类添加到哈希表中?

以及如何读取值并调用哈希表中的类方法?

4

3 回答 3

5

您可以使用委托。例如,如果您有以下方法:

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>

于 2012-04-18T01:19:32.450 回答
1

实际上,C# 编译器会将switch字符串实现为哈希表,因此您不太可能通过手动执行来获得任何东西。

看到这个帖子

你甚至可以告诉你的老板你已经做到了,而且你不会撒谎;)

于 2012-04-18T01:35:07.357 回答
0

以下代码允许您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.
于 2012-04-18T03:05:30.450 回答