usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Text;usingWebMatrix.Data;/// <summary>/// Summary description for ClassName/// </summary>publicclassBase{publicvoidCalculateTotalPriceInCart(varPartNumber,varDescription,varOrderId,boolIsBoxed){vardatabase=Database.Open("OSF");varquery="";varresult="";decimalprice=0.00M;if(IsBoxed){// Select item.query="SELECT Boxes, BoxPrice FROM Cart WHERE OrderId = '"+OrderId+"' AND PartNumber = '"+PartNumber+"' AND Description = '"+Description+"' AND IsBoxed = 1";result=database.Query(query);// Recalculate Price.foreach(variteminresult){price=result.Boxes*result.BoxPrice;}// Update item.query="UPDATE Cart SET BoxPrice = '"+price+"' WHERE OrderId = '"+OrderId+"' AND PartNumber = '"+PartNumber+"' AND Description = '"+Description+"' AND IsBoxed = 1";database.Execute(query);}}}
為什麼
var 只能在宣告並初始化後才可以在 method 的 scope 使用,不能在 global scope 使用和當作參數使用。
因為編譯器無法知道 CalculateTotalPriceInCart 必須要接到的參數的 data type 是什麼。
解決方法
將 CalculateTotalPriceInCart 所接收到的參數的資料型態變成 strongly data type。
usingSystem;usingSystem.Collections.Generic;usingSystem.Web;usingSystem.Text;usingWebMatrix.Data;/// <summary>/// Summary description for ClassName/// </summary>publicclassBase{// var 不能當作參數的型態傳入,參數的資料型態必須是強型別的資料型態。publicvoidCalculateTotalPriceInCart(IEnumerable<dynamic>Description,stringPartNumber,stringOrderId,boolIsBoxed){vardatabase=Database.Open("OSF");varquery="";varresult="";decimalprice=0.00M;if(IsBoxed){// Select item.query="SELECT Boxes, BoxPrice FROM Cart WHERE OrderId = '"+OrderId+"' AND PartNumber = '"+PartNumber+"' AND Description = '"+Description+"' AND IsBoxed = 1";result=database.Query(query);// Recalculate Price.foreach(variteminresult){price=result.Boxes*result.BoxPrice;}// Update item.query="UPDATE Cart SET BoxPrice = '"+price+"' WHERE OrderId = '"+OrderId+"' AND PartNumber = '"+PartNumber+"' AND Description = '"+Description+"' AND IsBoxed = 1";database.Execute(query);}}}