C#Action ,传递函数作为参数
问题描述:
我想将一个条件作为Action传递给另一个方法。在“ComputerPriceGenerator”第一线工作,但如何使阵列工作(第二行)?..任何想法C#Action <T>,传递函数作为参数
我要找的意见...,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;
}
答
你CalculatePrice
方法不应仅举Action
,IMO - 这两种方法应采取Action<Computer>
。所以,我有这样的方法:
public static void CalculatePrice(Computer computer, Action<Computer> action)
public static void CalcuateAllPrices(IEnumerable<Computer> computers,
Action<Computer> action)
,并呼吁他们这样的:
PriceMachine.CalculatePrice(cart.Computers[0], ComputerConverter);
PriceMachine.CalculateAllPrice(cart.Computers, ComputerConverter);
答
由于您想将该方法应用于数组的所有元素,因此您不会遍历它。
您可以定义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
并通过每一个匿名函数。
您的代码将是一个伟大的候选人使用LINQ,但它是完全的副作用。我会考虑重构。 – 2011-01-31 23:52:45
没有显示CalculatePrice和CalculateAllPrice的签名,很难知道如何帮助你。 – 2011-01-31 23:53:14
@Jon Skeet:看起来他似乎正在部分寻找关于“CalculateAllPrice”签名应该是什么的建议。虽然我可能是错的。 – 2011-01-31 23:57:43