将一个类“委托”到方法内部

时间:2013-10-17 22:11:26

标签: c#

我有以下内容:

Calculator cl = new Calculator();

我有一个方法课:

public class Testing {
  public void Calc(int x) {
  }
}

我想将一个计算器委托给Calc方法,以便可以在Calc中使用。

这有意义吗?我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

很难说出你究竟在问什么。但是如果Calculator类表示某种“服务”Testing类意图使用,那么通常的方法是使用字段:

public class Testing
{
  private readonly Calculator calculator = new Calculator();

  public void Calc(int x)
  {
    // use calculator here
  }
}

如果Calculator实际上是可配置的,或类似的东西,并且您不想在Testing内初始化它,那么您可以将其作为构造函数参数:

public class Testing
{
  private readonly Calculator calculator;

  public Testing(Calculator calculator)
  {
    this.calculator = calculator;
  }

  public void Calc(int x)
  {
    // use calculator here
  }
}

答案 1 :(得分:1)

svick的答案完全正确,更适合您描述的问题。但是既然你提到了代表,那么你可以在你的例子的上下文中使用它:

public static class Testing
{
    public static long Calc(long x, long y, Func<long, long, long> function)
    {
        if (function == null) throw new ArgumentNullException("function");
        return function(x, y);
    }

    static void Main()
    {
        Func<long, long, long> add = delegate(long a, long b) { return a + b; };
        Func<long, long, long> multiply = (a, b) => a * b;

        Console.WriteLine("3+2 = {0}", Calc(3, 2, add);
        Console.WriteLine("6*7 = {0}", Calc(6, 7, multiply);
        Console.WriteLine("3^2 = {0}", Calc(3, 2, (a, b) => Math.Pow(a, b));
    }
}

这是delegates和lambdas的一个相当愚蠢的应用,但它确实揭示了他们的力量。

答案 2 :(得分:0)

您可能会发现委托类型很有用。他们避开了Func<int, int, int> - 到处陷阱。如果函数的签名发生更改,则可以更轻松地修改现有代码。

您也可以将委托本身作为属性。

public class Testing {
    // this is the signature of the method we'd like to use to calculate.
    public delegate int Calculator(int a, int b);

    public Calculator Calc { get; set; }

    public Testing() {
        this.Calc = (x, y) => {
            throw new Exception("You haven't set a calculator!");
        };
    }

    public Testing(Calculator calc) {
        this.Calc = calc;
    }

    public int CalcWithOne(int x) {
        return Calc(1, x);
    }
}

然后你可以像

一样使用
Testing test = new Testing((x, y) => x + y);
// or
Testing test = new Testing();
test.Calc = (x, y) => x + y;
// then
test.Calc(2, 3); // 5
test.CalcWithOne(7); // 8