把一个方法传入委托,想根据委托里面的字段属性值,作为这个方法的参数,如何实现?
目前是方法传入委托的时候就把参数定好。
如下面的代码,lambda中SumPrices(1)的参数是定好的,想根据委托里面的Data值作为SumPrices的参数,最终实现SumPrices(Data)
1 static void Main(string[] args) 2 { 3 Order order = new Order("0001"); 4 order.items.Add(new Item() { ItemUsingType = 1, Price = 10.0F }); 5 order.items.Add(new Item() { ItemUsingType = 1, Price = 15.0F }); 6 order.items.Add(new Item() { ItemUsingType = 2, Price = 20.0F }); 7 order.items.Add(new Item() { ItemUsingType = 2, Price = 30.0F }); 8 9 IBusinessService service = new BusinessService(); 10 object result = service.SendBusinessData<Order>(o => { return o.SumPrices(1); }, order); 11 Console.WriteLine(result); 12 Console.ReadKey(); 13 }
委托:
public interface IBusinessService { object SendBusinessData<P>(Func<P, object> callFun, P param); } public class BusinessService : IBusinessService { private int Data;
public object SendBusinessData<P>(Func<P, object> callFun,P param) { Data = 2; //如何把Data作为callFun的参数? object result = callFun(param); return result; } }
实体类:
1 public class Order 2 { 3 public string Id { get; set; } 4 public IList<Item> items { get; set; } 5 6 public Order(string id) 7 { 8 this.Id = id; 9 items = new List<Item>(); 10 } 11 12 public double SumPrices(int itemUsingType) 13 { 14 double resultPrices = 0.00; 15 var currentItems = items.GroupBy(item => item.ItemUsingType).Single(group => group.Key == itemUsingType); 16 if (currentItems.Count() > 0) 17 { 18 foreach (var item in currentItems) 19 { 20 resultPrices += item.Price; 21 } 22 } 23 return resultPrices; 24 } 25 } 26 27 public class Item 28 { 29 /// <summary> 30 /// Item price. 31 /// </summary> 32 public float Price { get; set; } 33 34 /// <summary> 35 /// Item using type. 36 /// </summary> 37 public int ItemUsingType { get; set; } 38 }