我正在尝试在C#中的哈希表中存储方法列表,因此我可以在用户输入所需的密钥时立即执行该方法。我想知道我会怎么做。我被告知我可以使用匿名接口或代理来执行此操作。哪个更好?为什么?我没有找到太多关于这实际上会如何实现的参考。
示例:
key = method
" +" = object.add
" - " = object.minus
答案 0 :(得分:5)
这是一个过于简化的解决方案,但它说明了完成您的要求所需的步骤。
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();
}
}
答案 1 :(得分:0)
在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);