using System;
namespace DelegateExample.Controllers
{
public class CalculationController : BaseController
{
private Int32 dependentVariable;
public RenderJsonResult Go(string act, string one, string two)
{
//Step One: Prep Chain of Delegates
dependentVariable = Convert.ToInt32(one);
Func<Int32,Int32> mathDelegate;
mathDelegate = Adder;
mathDelegate += Multiplier;
mathDelegate += Reducer;
//Step Two: Use Delegate with Numeric Data
Int32 thirdValue = mathDelegate(Convert.ToInt32(two));
var result = new { calulation = thirdValue.ToString() };
return RenderJson(result);
}
private Int32 Adder(Int32 independentVariable)
{
dependentVariable = dependentVariable + independentVariable;
return dependentVariable;
}
private Int32 Multiplier(Int32 independentVariable)
{
dependentVariable = dependentVariable * independentVariable;
return dependentVariable;
}
private Int32 Reducer(Int32 independentVariable)
{
dependentVariable = dependentVariable - independentVariable;
return dependentVariable;
}
}
}
The code offers a refactoring of the controller here. (The act string is used for nothing.) What happens? Two variables will be handed in. The first will be kept in a private field. The second will be used to mess with the value of the private field once it has been set. If 5 and 7 are handed in then 5 will go into the private field and 7 will be used to alter the 5. We use += to shove numerous methods into our delegate in a precession. All of the methods will be handed the 7 to use in effecting the contents of the private field. The methods will fire off in the order they were specified by way of += concatenation. The methods do not hand data from one method to the next. (The return data is ignored until the very last method runs.) Instead, a private field is used to manage state. 7 gets added to 5 making it 12. 7 gets multiplied against 12 making it 84. 7 gets subtracted from 84 making it 77. 77 is returned to us. This is another something I learned from "C# 4.0 in a Nutshell."
No comments:
Post a Comment