我的代表......
private delegate double CalculateDelegate(double x, double y);
声明代表的代码......
private CalculateDelegate calculate;
我与代表一起使用的方法......
private double Add(double x, double y) { return x + y; }
private double Subtract(double x, double y) { return x - y; }
我如何执行所需的方法...
calculate = new CalculateDelegate(Add);
...或
calculate = new CalculateDelegate(Subtract);
这有效,但由于实际代码包含更多“函数”,我想避免使用switch / IF语句。所以我需要的是编写新方法发送它。
计算方法(我在这里使用的行动认为它可能有效,但它没有)
public double calc(Action methodName, double x, double y)
{
calculate = new CalculateDelegate(methodName);
return calculate(x,y);
}
我想如何执行所需的方法。
public void go()
{
calc(Add, 5,4);
}
这可能没有反思吗?
答案 0 :(得分:3)
这个shm_overview(7)
怎么样,只需使用代码名称相等的代码字典,看看例子。:
public delegate double CalculateDelegate(double x, double y);
public class Test
{
public CalculateDelegate calculate;
}
public class DelegateContainer
{
public double Add(double x, double y)
{
return x + y;
}
public double Subtract(double x, double y)
{
return x - y;
}
public Dictionary<string, CalculateDelegate> collection = new Dictionary<string, CalculateDelegate>();
public DelegateContainer()
{
collection["Add"] = Add;
collection["Subtract"] = Subtract;
}
public CalculateDelegate this[string name]
{
get
{
return collection[name];
}
}
}
public static void Main()
{
var target = new Test();
var container = new DelegateContainer();
target.calculate = container["Add"];
Console.WriteLine("1 + 2 = " + target.calculate(1, 2));
target.calculate = container["Subtract"];
Console.WriteLine("5 - 2 = " + target.calculate(5, 2));
}