【问题标题】:how to store methods in a hash table?如何将方法存储在哈希表中?
【发布时间】:2017-07-31 09:46:19
【问题描述】:

我正在尝试将方法列表存储在 C# 中的哈希表中,以便在用户输入所需的密钥后立即执行该方法。我想知道我将如何做到这一点。有人告诉我,我可以同时使用匿名接口或委托来执行此操作。哪个更好?为什么?不过,我还没有找到太多关于这实际上是如何完成的参考。

例子:

key = 方法

"+" = object.add

"-" = object.minus

【问题讨论】:

  • 检查delegateAction
  • 2017年你不应该使用Hashtable,你应该使用Dictionary<string, yourdelegatetype>

标签: c# object methods hashtable


【解决方案1】:

这是一个过于简单的解决方案,但它说明了完成您的要求所需的步骤。

public class Test
{
    // Ok, we declare the hashtable here. It could be a Dictionary though, so we don't have to
    // cast it. But you requested a hashtable.
    private Hashtable hash = new Hashtable();

    // Were it a dictionary, we'd have:
    // private Dictionary<string, Calculation> dict = new Dictionary<string, Calculation>();

    // We declare the signature of the methods that we will store. This means that we accept any
    // methods which receive two decimal parameters and return a decimal output
    private delegate decimal Calculation(decimal x, decimal y);

    public Test()
    {
    }

    public void Run()
    {
        // A sample implementation of the delegate
        Calculation sum = (decimal x, decimal y) =>
        {
            return x + y;
        };

        // Another sample implementation
        Calculation minus = (decimal x, decimal y) =>
        {
            return x - y;
        };

        // Here we add both of them to the hashtable
        this.hash.Add("+", sum);
        this.hash.Add("-", minus);

        // Were it a dictionary, we'd have:
        // this.dict.Add("+", sum);
        // this.dict.Add("+", minus);

        // Note that in the hashtable you can put ANYTHING. Were it a dictionary, it would be strong-typed and
        // we'd be able to only add Calculation types

        // Now ask the user for input values
        Console.Write("X: ");
        var xInput = decimal.Parse(Console.ReadLine());

        Console.Write("Y: ");
        var yInput = decimal.Parse(Console.ReadLine());

        // Ask the user which method to execute
        Console.WriteLine("Which method to execute? Enter number:");
        Console.WriteLine("1. +");
        Console.WriteLine("2. -");
        Console.Write("> ");

        var choice = int.Parse(Console.ReadLine());

        // Get the selected method from the hashtable
        Calculation calc;
        if (choice == 1)
        {
            calc = (Calculation)this.hash["+"];
        }
        else if (choice == 2)
        {
            calc = (Calculation)this.hash["-"];
        }
        else
        {
            throw new ArgumentOutOfRangeException();
        }

        // Were it a dictionary, we'd have (note that we don't have to cast it):
        // calc = this.dict["-"];

        // execute it, and output the result
        Console.WriteLine("Result: " + calc(xInput, yInput));

        Console.ReadKey();
    }
}

【讨论】:

    【解决方案2】:

    在 C# 中存储方法引用有一个类型叫做 Delegate。您应该使用代表字典。首先,您必须定义一个与您的方法签名匹配的委托。想象一下,您有一个返回 int 并接受两个 int 作为参数的方法列表。首先,您为此定义委托。

     public delegate int SomeMethodsHandler(int a,int b);
    

    然后你创建你的方法。

    public int MethodA(int a,int b)
    {
          // do some work here
          return 0;
    }
    
     public int MethodB(int a,int b)
    {
          // do some work here
          return 1;
    }
    
     public int MethodC(int a,int b)
    {
          // do some work here
          return 2;
    }
    

    然后你创建 Dictionary 来存储这些方法。

     Dictionary<string,SomeMethodsHandler> methods = new Dictionary<string,SomeMethodsHandler>();
    
     methods["A"] = MethodA;
     methods["B"] = MethodB;
     methods["C"] = MethodC;
    

    再次调用该方法。

     int a = methods["A"](5,7);
    

    【讨论】:

    • nice .. 你能告诉 HOWWHEN 这种类型的调用有帮助吗?
    • 这里的问题是如何将方法存储在键值对结构中。你的问题是我从来没有遇到过我需要在字典中存储方法引用的那种情况。但是,当您需要实现观察者模式或执行某种功能性工作时,委托本身非常有用。
    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2013-08-27
    • 2023-03-22
    • 1970-01-01
    • 2017-01-22
    • 2015-07-18
    相关资源
    最近更新 更多