我正在使用LINQ在主类的开头将一堆对象从XML加载到' var'中。我正在努力实施“战略”。虽然我的程序中有模式,但我需要引用' var'在这些战略类中。
我有什么方法可以做到这一点?我的理解通常是我会使用静态变量,但这似乎不适用于' var'?
static void Main(string[] args)
{
// Below code loads the XML file and builds Product objects with LINQ
XDocument XDoc = XDocument.Load("inventory.xml");
IEnumerable<Product> products = from q in XDoc.Descendants("product")
select new Product
{
RecordNumber = Convert.ToInt32(q.Element("recordNumber").Value),
Name = q.Element("name").Value,
Stock = Convert.ToInt32(q.Element("stock").Value),
Price = Convert.ToInt32(q.Element("price").Value),
CartQuantity = 0,
CartPrice = 0
};
// Builds one instance of the cart that will be used to hold products
Cart ShoppingCart = new Cart();
Console.WriteLine("WELCOME TO CONSOLE-BASED SHOPPING CART!");
Start:
Console.WriteLine("Following options are available: \n" +
"1. Add an item to cart, \n" +
"2. Remove an item from the cart, \n" +
"3. View the cart \n" +
"4. Checkout and Pay \n" +
"5. Exit \n");
String input = Console.ReadLine();
Context context;
和其他类:
public class Cart : System.Collections.IEnumerable
{
//Cart class - one instance is created to hold all the user's items
//Includes methods to add, remove and check if cart contains an item
// Also includes enumerator
private List<Product> items;
public Cart()
{
items = new List<Product>();
}
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < items.Count; i++)
{
yield return items[i];
}
}
public void AddItem(Product prod)
{
items.Add(prod);
}
public void RemoveProduct(Product prod)
{
items.Remove(prod);
}
public int CartCount()
{
return items.Count();
}
public void WriteToConsole()
{
Console.WriteLine("{0,16} {1, 16} {2, 16} {3, 16}","Item No.", "Item", "Amount", "Price");
int TotalCost = 0; //Iterator below allows us to work out total price
foreach (Product x in this)
{
Console.WriteLine("{0,16} {1, 16} {2, 16} {3, 16}", x.RecordNumber, x.Name, x.CartQuantity, x.CartPrice);
TotalCost = TotalCost + x.CartPrice;
}
Console.WriteLine("");
Console.WriteLine("Total Price: {0,54}", TotalCost);
}
public void Reset()
{
foreach (Product x in this)
{
this.RemoveProduct(x);
x.CartQuantity = 0;
x.CartPrice = 0;
}
}
public class Product
{
// Product class - objects are built using LINQ in main method
public int RecordNumber { get; set; }
public String Name { get; set; }
public int Price { get; set; }
public int Stock { get; set; }
public int CartQuantity { get; set; }
public int CartPrice { get; set; }
public Product() { }
}
答案 0 :(得分:0)
var
只是一个关键字,告诉编译器推断变量的类型。例如, 不会创建动态类型的变量。
在此处显示的特定情况下,products
的类型将为IEnumerable<Product>
。因此,如果您将var
替换为IEnumerable<Product>
,那么您将看到相同的行为。 (事实上,这正是编译器正在做的事情 - 如果你看看C#编译器生成的IL,本地将有类型IEnumerable<Product>
!)
C#禁止在声明除本地之外的任何内容时使用var
。例如,如果要声明字段,则需要使用显式类型。您选择哪种类型取决于该字段需要保留的特定数据类型,因此我无法提供适用于每种情况的答案。 (在某些情况下,您可能希望使用表达式的类型,在其他情况下,您可能希望使用接口类型。)