public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { if (context.Options.IgnoreOfferPrice) { // Ignore offer price for this calculation. await next(context); return; } var product = context.Product; if (product.SpecialPrice.HasValue) { // Check date range. var now = DateTime.UtcNow; var from = product.SpecialPriceStartDateTimeUtc; var to = product.SpecialPriceEndDateTimeUtc; if ((from == null || now >= from) && (to == null || now <= to)) { context.OfferPrice = product.SpecialPrice; context.FinalPrice = product.SpecialPrice.Value; } } await next(context); }
//Depending upon request we will assign Delegate public CalculatorDelegate GetDelegateRef(int intoperation) { //And Finally assign based on request switch (intoperation) { case 1: delegateObj = Add; break; case 2: delegateObj = Sub; break; case 3: delegateObj = Multi; break; case 4: delegateObj = Div; break; default: break; } return(delegateObj); }
//Depending upon request we will assign Delegate public CalculatorDelegate GetDelegateRef(int intoperation) { //And Finally assign based on request switch (intoperation) { case 1: delegateObj = (a, b) => a + b; break; case 2: delegateObj = (a, b) => a - b; break; case 3: delegateObj = (a, b) => a * b; break; case 4: delegateObj = (a, b) => a / b; break; default: break; } return(delegateObj); }
private static void AddSubtractDelegate() { CalculatorDelegate addDel = Add; CalculatorDelegate subDel = Subtract; CalculatorDelegate mulDel = Multiply; CalculatorDelegate divDel = Divide; // won't work, has to be a CalculatorDelegate // CalculatorDelegate multiCalc = Add + Subtract; // this will work CalculatorDelegate multiCalc = addDel + subDel; multiCalc += mulDel; multiCalc += divDel; Console.WriteLine($"Invoking multiCalc (four methods)"); multiCalc(8, 2); // remove delegates // this doesn't work in .net core multiCalc = multiCalc - subDel; multiCalc -= mulDel; Console.WriteLine($"Invoking multiCalc (two methods)"); multiCalc(8, 2); }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; var options = context.Options; // Ignore tier prices of bundle items (BundlePerItemPricing). var processTierPrices = !options.IgnoreTierPrices && !options.IgnoreDiscounts && product.HasTierPrices && context.BundleItem?.Item == null; if (processTierPrices) { var tierPrices = await context.GetTierPricesAsync(); // Put minimum tier price to context because it's required for discount calculation. context.MinTierPrice = GetMinimumTierPrice(product, tierPrices, context.Quantity); if (context.Options.DetermineLowestPrice && !context.HasPriceRange) { context.HasPriceRange = tierPrices.Any() && !(tierPrices.Count == 1 && tierPrices.First().Quantity <= 1); } } // Process the whole pipeline. We need the result of discount calculation. await next(context); if (processTierPrices && context.MinTierPrice.HasValue) { // Apply the minimum tier price if it achieves a lower price than the discounted FinalPrice. context.FinalPrice = Math.Min(context.FinalPrice, context.MinTierPrice.Value); } }
public int multiply(int x, int y) { CalculatorDelegate <int> multi = delegate(int x, int y) { return(x * y); }; return(multi(x, y)); }
public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; if (product.ProductType != ProductType.GroupedProduct) { // Proceed with pipeline and omit this calculator, it is made for grouped products only. await next(context); return; } var options = context.Options; if (options.IgnoreGroupedProducts) { await next(context); return; } await EnsureAssociatedProductsAreLoaded(product, context); if (context.AssociatedProducts.Count == 0) { // No children, get out. return; } CalculatorContext lowestPriceCalculation = null; if (options.DetermineLowestPrice && context.AssociatedProducts.Count > 1) { foreach (var associatedProduct in context.AssociatedProducts) { // Get the final price of associated product var childCalculation = await CalculateChildPriceAsync(associatedProduct, context); if (lowestPriceCalculation == null || childCalculation.FinalPrice < lowestPriceCalculation.FinalPrice) { // Set the lowest price calculation lowestPriceCalculation = childCalculation; } } lowestPriceCalculation.HasPriceRange = true; } else { // Get the final price of first associated product lowestPriceCalculation = await CalculateChildPriceAsync(context.AssociatedProducts.First(), context); } // Copy data from child context to this context lowestPriceCalculation.CopyTo(context); }
static void Main(string[] args) { objCalculatorDelegate = new CalculatorDelegate(GetMulti); for (int i = 1; i <= 10; i++) { //4 开始发布任务并同时执行多个任务 objCalculatorDelegate.BeginInvoke(10 * i, 1000 * i, MyCallback, i); } Console.ReadLine(); }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; var bundleItem = context.BundleItem; Discount appliedDiscount = null; if (bundleItem?.Item != null) { var bi = bundleItem.Item; if (bi.Discount.HasValue && bi.BundleProduct.BundlePerItemPricing) { appliedDiscount = new Discount { UsePercentage = bi.DiscountPercentage, DiscountPercentage = bi.Discount.Value, DiscountAmount = bi.Discount.Value }; context.AppliedDiscounts.Add(appliedDiscount); var discountAmount = appliedDiscount.GetDiscountAmount(context.FinalPrice); context.FinalPrice -= discountAmount; } } else if (!context.Options.IgnoreDiscounts && !product.CustomerEntersPrice) { // Don't calculate when customer entered price or discounts should be ignored in any case. var applicableDiscounts = await GetApplicableDiscounts(product, context); if (applicableDiscounts.Any()) { appliedDiscount = applicableDiscounts.GetPreferredDiscount(context.FinalPrice); if (appliedDiscount != null) { context.AppliedDiscounts.Add(appliedDiscount); var discountAmount = appliedDiscount.GetDiscountAmount(context.FinalPrice); context.FinalPrice -= discountAmount; } } } // Percentage discount on minimum tier price. if (!context.Options.IgnorePercentageDiscountOnTierPrices && context.MinTierPrice.HasValue && context.MinTierPrice != decimal.Zero && appliedDiscount != null && appliedDiscount.UsePercentage) { context.FinalPrice -= appliedDiscount.GetDiscountAmount(context.MinTierPrice.Value); } await next(context); }
private static void CombineDelegates() { CalculatorDelegate calc = (CalculatorDelegate)Delegate.Combine(new CalculatorDelegate[] { Add, Subtract, Multiply, Divide }); Delegate[] list = calc.GetInvocationList(); Console.WriteLine($"Total delegates in calc: {list.Length}"); calc(6, 3); }
public void Test() { CalculatorDelegate cal1 = Add; CalculatorDelegate cal2 = delegate(int a, int b) { return(a + b); }; CalculatorDelegate cal3 = (int a, int b) => { return(a + b); }; CalculatorDelegate cal4 = (a, b) => a + b; Console.WriteLine("通过匿名方法调用:" + cal4(10, 20)); }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { if (!context.Options.DetermineLowestPrice) { // Proceed with pipeline and omit this calculator, it is made for lowest price calculation only. await next(context); return; } // Process the whole pipeline with maximum quantity to get the minimum tier price applied. context.Quantity = int.MaxValue; await next(context); // Get lowest possible price. var product = context.Product; var lowestPrice = context.FinalPrice; var forceApply = false; if (product.LowestAttributeCombinationPrice.HasValue && product.LowestAttributeCombinationPrice.Value < lowestPrice) { lowestPrice = product.LowestAttributeCombinationPrice.Value; } if (lowestPrice == decimal.Zero && product.Price == decimal.Zero) { // Do not display 0 as lowest price. forceApply = true; lowestPrice = product.LowestAttributeCombinationPrice ?? decimal.Zero; } // Apply lowest price. if (lowestPrice < context.FinalPrice || forceApply) { context.FinalPrice = lowestPrice; } context.LowestPrice = context.FinalPrice; // Check whether the product has a price range. if (!context.HasPriceRange) { context.HasPriceRange = product.LowestAttributeCombinationPrice.HasValue; } if (!context.HasPriceRange) { var attributes = await context.Options.BatchContext.Attributes.GetOrLoadAsync(product.Id); context.HasPriceRange = attributes.Any(x => x.ProductVariantAttributeValues.Any(y => y.PriceAdjustment != decimal.Zero)); } }
public static void Main(string[] args) { Calculator c1 = new Calculator(); //Instantiate Delegate Object CalculatorDelegate cd1 = new CalculatorDelegate(c1.Add); //Multi cast Delegate cd1 += c1.Sub; //Invoke var x = cd1.Invoke(10, 10); Console.WriteLine(x); }
static void Main(string[] args) { #region 匿名类与var var obj = new { age = 20, name = "小张", id = 10001 }; Console.WriteLine("姓名:{0},年龄:{1},学号:{2}", obj.name, obj.age, obj.id); var b = "adadad"; //var arry = { 1, 2, 3 }; //var arry1 = new int[] { 1, 2, 3 }; //var a = null; #endregion #region 扩展方法 Console.WriteLine("-----------扩展方法---------------"); ExtendMethodTest(); ExtendSrudentTest(); #endregion #region 委托 Console.WriteLine("-------------委托-------------"); //3将委托与方法关联:即创建委托对象关联方法 CalculatorDelegate objAdd = new CalculatorDelegate(Add); //4通过委托调用方法 int result = objAdd(3, 6); Console.WriteLine(result); //断开委托所关联的方法 objAdd -= Add; //关联减法 objAdd += Sub; Console.WriteLine(objAdd(20, 10)); #endregion #region 匿名方法与Lambal表达式 Console.WriteLine("-------匿名方法-------"); CalculatorDelegate add = delegate(int c, int d) { return(c + d); }; Console.WriteLine(add(20, 30)); Console.WriteLine("---Lambal表达式---"); CalculatorDelegate add1 = (int c, int d) => { return(c + d); }; Console.WriteLine(add1(20, 30)); CalculatorDelegate add2 = (c, d) => { return(c + d); }; Console.WriteLine(add2(5, 5)); MathDelegate math = a => a * a; Console.WriteLine(math(10)); #endregion Console.ReadLine(); }
static void Main(string[] args) { //3创建委托对象 CalculatorDelegate objCal = new CalculatorDelegate(Add); //4通过使用委托调用方法 Console.WriteLine("a+b=" + objCal(30, 20)); //5通过动态更改委托指针指向的方法,进行方法切换 objCal = Sub; //objCal -= Add; //objCal += Sub; Console.WriteLine("a-b=" + objCal(30, 20)); Console.ReadLine(); }
public override async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; if (product.ProductType != ProductType.BundledProduct) { // Proceed with pipeline and omit this calculator, it is made for product bundles only. await next(context); return; } if (product.BundlePerItemPricing) { if (context.Options.DetermineLowestPrice) { context.HasPriceRange = true; } await EnsureBundleItemsAreLoaded(product, context); context.FinalPrice = decimal.Zero; foreach (var bundleItem in context.BundleItems) { // Get the final unit price of bundle item part product. // No need to pass bundleItem.Item.Quantity. The pipline always calculates a unit price. var childCalculation = await CalculateChildPriceAsync(bundleItem.Item.Product, context, c => { c.Quantity = 1; c.AssociatedProducts = null; c.BundleItems = null; c.BundleItem = bundleItem; c.AdditionalCharge = decimal.Zero; c.MinTierPrice = null; }); // Add price of part to root final price (unit price * contained quantity in this bundle). context.FinalPrice += decimal.Multiply(childCalculation.FinalPrice, bundleItem.Item.Quantity); // TODO: (mg) (core) Is it not better to continue the pipeline here (unlike in Smartstore classic)? Continuation could // apply OfferPrice and/or further discounts to the automatically calculated final price here. TBD with MC please. } } else { // Continue pipeline await next(context); } }
static void Main(string[] args) { //【3】创建委托对象,关联“具体方法” CalculatorDelegate objCal = new CalculatorDelegate(Add); //【4】通过委托调用方法,而不是直接使用方法 int result = objCal(8, 23); Console.WriteLine("8+23={0}", result); objCal -= Add; //断开当前委托对象所关联的方法 objCal += Sub; //重新指向一个新的方法 result = objCal(8, 23); Console.WriteLine("8-23={0}", result); Console.ReadLine(); }
static void Main(string[] args) { //System.Predicate Calculator calculator = new Calculator(); CalculatorDelegate calculatorAdd = calculator.Add; Console.WriteLine(calculatorAdd(10, 5)); calculatorAdd += calculator.Subtract; Console.WriteLine(calculatorAdd(10, 5)); calculatorAdd += Multiply; Console.WriteLine(calculatorAdd(10, 5)); Console.ReadLine(); }
static void Main(string[] args) { //【3】创建委托对象,关联具体方法 CalculatorDelegate objCal = new CalculatorDelegate(Add); //【4】通过委托去调用方法,而不是直接使用方法 // int result = objCal(10, 20); //objCal -= Add;//断开委托对象和具体方法的关联 objCal += Sub; int result = objCal(10, 20); Console.WriteLine("a+b=" + result); Console.ReadLine(); }
public void setOperation(CalculatorDelegate CalculatorOperator) { //this code allow the calculator to perform a result OR change the operation when an new(or the same) operation is called if (Operands.ToArray().Length == 2 && this.CalculatorOperator != null) { //Update the result using the previous operator before set the actual operator if (ActualOperand() == "") { Operands.Pop(); //Remove to be added again, important to keep just 2 operands in the stack } else { ProcessResult(); } } this.CalculatorOperator = CalculatorOperator; }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; var options = context.Options; if (!options.IgnoreTierPrices && !options.IgnoreDiscounts && product.HasTierPrices) { // TODO: (core) Really check IgnoreDiscounts here? var tierPrice = await GetMinimumTierPriceAsync(product, options.Customer, context.Quantity, options.BatchContext); if (tierPrice.HasValue) { // TODO ... } } await next(context); }
/// <summary> /// 异步执行 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnTask2_Click(object sender, EventArgs e) { //3实例化委托对象 并赋值需要引用的方法 CalculatorDelegate objCalculatorDelegate = ExecTask1; //1开始异步调用 //通过委托的BeginInvoke方法进行异步调用 //BeginInvoke是异步调用的核心 IAsyncResult result = objCalculatorDelegate.BeginInvoke(35, null, null); //2并行执行其他任务 lblResult1.Text = "正在计算,请稍等..."; lblResult2.Text = ExecTask2(55).ToString(); //3获取异步执行结果 借助IAsyncResult接口对象 不断查询异步调用是否结束 //该接口对象有异步调用方法的所有参数,调用结束后取出结果作为返回值 int r = objCalculatorDelegate.EndInvoke(result); lblResult1.Text = r.ToString(); }
public CalculatorDelegate GetDelegateRef(int intoperation) { switch (intoperation) { case 1: delegateObj = Add; break; case 2: delegateObj = Sub; break; case 3: delegateObj = Multi; break; case 4: delegateObj = Div; break; } return delegateObj; }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { if (context.Options.IgnoreDiscounts) { // Ignore discounts for this calculation (including discounts for bundle items). await next(context); return; } var minTierPrice = context.MinTierPrice ?? 0; // Percentage discount on minimum tier price. // TODO: (mg) (core) PercentageDiscountOnTierPrices must be tested thoroughly. It is not entirely clear whether this works correctly in all cases. if (!context.Options.IgnorePercentageDiscountOnTierPrices && minTierPrice != 0) { var(discountAmountOnTierPrice, discountOnTierPrice) = await GetDiscountAmountAsync(minTierPrice, context); if (discountOnTierPrice != null && discountOnTierPrice.UsePercentage) { context.AppliedDiscounts.Add(discountOnTierPrice); context.DiscountAmount += discountAmountOnTierPrice; context.FinalPrice -= discountAmountOnTierPrice; await next(context); return; } } // Discount on final price. var(discountAmount, appliedDiscount) = await GetDiscountAmountAsync(context.FinalPrice, context); if (appliedDiscount != null) { context.AppliedDiscounts.Add(appliedDiscount); context.DiscountAmount += discountAmount; context.FinalPrice -= discountAmount; } await next(context); }
private static void RemoveDelegate() { CalculatorDelegate divDel = Divide; CalculatorDelegate calc = (CalculatorDelegate)Delegate.Combine(new CalculatorDelegate[] { Add, Subtract, Multiply, Divide }); Delegate[] list = calc.GetInvocationList(); Console.WriteLine($"Total delegates in calc: {list.Length}"); calc(6, 3); CalculatorDelegate newCalc = (CalculatorDelegate)Delegate.Remove(calc, divDel); Console.WriteLine($"Total delegates in calc: {newCalc.GetInvocationList().Length}"); newCalc(6, 4); }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; var options = context.Options; var processTierPrices = !options.IgnoreTierPrices && !options.IgnoreDiscounts && product.HasTierPrices && context.BundleItem == null; if (processTierPrices) { var tierPrices = await context.GetTierPricesAsync(); // Put minimum tier price to context because it's required for discount calculation. context.MinTierPrice = GetMinimumTierPrice(product, tierPrices, context.Quantity); if (context.Options.DetermineLowestPrice && !context.HasPriceRange) { context.HasPriceRange = tierPrices.Any() && !(tierPrices.Count == 1 && tierPrices.First().Quantity <= 1); } } // Process the whole pipeline. We need the result of discount calculation. await next(context); if (processTierPrices && context.MinTierPrice.HasValue) { // Wrong result: //context.FinalPrice = Math.Min(context.FinalPrice, context.MinTierPrice.Value); // Apply the minimum tier price if it achieves a lower price than the discounted FinalPrice // but exclude additional charge from comparing. context.FinalPrice -= context.AdditionalCharge; if (context.MinTierPrice.Value < context.FinalPrice) { context.DiscountAmount += context.FinalPrice - context.MinTierPrice.Value; context.FinalPrice = context.MinTierPrice.Value; } context.FinalPrice += context.AdditionalCharge; } }
//This method executes calculations. public static double Calculate(string s) { CalculatorDelegate d = Calculator; if (s.Length < 3) { throw new ArgumentException("Input Error! Please, try again."); } string[] arr = ParsingHelper.MyParse(s); arr = Converter(arr, d); int i = 1; double res = Convert.ToDouble(arr[0]); while (i < arr.Length) { res = d(res, Convert.ToDouble(arr[i + 1]), arr[i]); i += 2; } return(res); }
static void Main(string[] args) { PrintNameDelegate printNameDelegate = new PrintNameDelegate(PrintName); printNameDelegate("Atanas"); Console.WriteLine("Result when pass the delegate as parameter to method."); PrintPersonInfo(printNameDelegate); Console.WriteLine("Store more than one method in delegate"); CalculatorDelegate calculatorDelegate = Sum; calculatorDelegate += Multiply; calculatorDelegate += Divide; calculatorDelegate -= Multiply; calculatorDelegate(100, 20); Console.WriteLine(); Console.WriteLine("Use annonymous function"); calculatorDelegate += (double firstNumber, double secondNumber) => Console.WriteLine($"{firstNumber} * {secondNumber} = {firstNumber * secondNumber}"); calculatorDelegate(20, 5); }
public async Task CalculateAsync(CalculatorContext context, CalculatorDelegate next) { var product = context.Product; if (product.SpecialPrice.HasValue) { // TODO: (mg) Does Bundle with ItemPricing has OfferPrice? // Check date range var now = DateTime.UtcNow; var from = product.SpecialPriceStartDateTimeUtc; var to = product.SpecialPriceEndDateTimeUtc; if ((from == null || now >= from) && (to == null || now <= to)) { // TODO: (mg) (core) Does it make sense here to set FinalPrice only when SpecialPrice is lower? context.OfferPrice = product.SpecialPrice; context.FinalPrice = product.SpecialPrice.Value; } } await next(context); }
static string[] Converter(string[] arr, CalculatorDelegate d) { int i = 1; string newstr = ""; while (i < arr.Length) { if (arr[i] == "(") { string[] tempArr = new string[100]; var j = i; var count = 0; while (arr[j] != ")") { tempArr[count] = arr[j]; } var tempStr = ""; var tempArr1 = Converter(tempArr, d); foreach (var s in tempArr1) { tempStr += s; } newstr += tempStr; } if (arr[i] == "+" || arr[i] == "-") { newstr += arr[i - 1] + arr[i]; i += 2; } else if (arr[i] == "*" || arr[i] == "/") { double temp = Convert.ToDouble(arr[i - 1]); while (true) { temp = d(temp, Convert.ToDouble(arr[i + 1]), arr[i]); if (i + 2 < arr.Length && (arr[i + 2] == "*" || arr[i + 2] == "/")) { i = i + 2; } else { break; } } newstr += temp; if (i + 2 < arr.Length) { newstr += arr[i + 2]; i += 4; } else { break; } } } if (arr[arr.Length - 2] == "+" || arr[arr.Length - 2] == "-") { newstr += arr[arr.Length - 1]; } return(MyParse(newstr)); }
public void MyCalculator(ref double initialNumber, CalculatorDelegate dc) { double result; dc(ref initialNumber, out result); System.Console.WriteLine(result.ToString()); }