简体   繁体   English

C#动作 <T> ,传递函数作为参数

[英]C# Action<T>, Pass function as parameter

I want to pass a condition as Action to another method. 我想将一个条件作为Action传递给另一个方法。 First line in "ComputerPriceGenerator" works, but how to make the array work (second line)?.. Any ideas “ComputerPriceGenerator”中的第一行有效,但如何使数组工作(第二行)?任何想法

I'm looking for advice..., CalculateAllPrice is not designed yet 我正在寻找建议......,CalculateAllPrice尚未设计

public void ComputerPriceGenerator()
{
    //Below line Works
    PriceMachine.CalculatePrice(cart.Computers[0],() => ComputerConverter(cart.Computers[0]));           
    //How to make this work, i don't want to loop it???
    PriceMachine.CalculateAllPrice(cart.Computers,() => ComputerConverter(??));
}

public void ComputerConverter(Computer comp)
{
    if (comp.Memory <= 2)
        comp.Discount = 10;
}

Your CalculatePrice method shouldn't take just Action , IMO - both methods should take Action<Computer> . 你的CalculatePrice方法应该只Action ,IMO - 两种方法都应该采取Action<Computer> So I would have the methods like this: 所以我会有这样的方法:

public static void CalculatePrice(Computer computer, Action<Computer> action)
public static void CalcuateAllPrices(IEnumerable<Computer> computers,
                                     Action<Computer> action)

and call them like this: 并称他们为:

PriceMachine.CalculatePrice(cart.Computers[0], ComputerConverter);
PriceMachine.CalculateAllPrice(cart.Computers, ComputerConverter);

As you want to apply the method to all elements of the array, you won't get around iterating over it. 由于您希望将该方法应用于数组的所有元素,因此您无法绕过它进行迭代。

You could define PriceMachine.CalculateAllPrice as such: 你可以这样定义PriceMachine.CalculateAllPrice

public void CalculateAllPrice(IEnumerable<Computer> data, Action<Computer> action)
{
  foreach(Computer c in data)
    action(c);
}
PriceMachine.CalculateAllPrice(cart.Computers, (Computer x) => ComputerConverter(x));

然后使CalculateAllPrice迭代通过cart.Computers并将每个传递给匿名函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM