对于下面的代码,main()方法中的foreach循环不显示任何值。即我的列表没有初始化显示。请帮我。提前谢谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
public static List<Product> allProducts;
public static void InitialiseMyProducts(List<Product> allProducts)
{
allProducts = new List<Product>
{
new Product(){Id=1,Name="TV"},
new Product(){Id=2,Name="Bat"},
new Product(){Id=3,Name="Ball"},
new Product(){Id=4,Name="Chair"},
};
}
public static void Main(string[] args)
{
List<Product> allProducts = new List<Product>();
allProducts = new List<Product>();
InitialiseProductList(allProducts);
foreach (Product res in allProducts)
{
Console.WriteLine("ID:" + " " + res.Id + " " + "Name:" + " " + res.Name);
}
Console.ReadKey();
}
}
}
答案 0 :(得分:6)
您有几个变量都叫allProducts
:
InitialiseMyProducts
Main
您在Main
中初始化本地变量两次,然后将其传递给InitialiseMyProducts
(或InitialiseProductList
- 您已将名称更改为中途)。但是,该方法然后忽略先前的值并更改参数以引用另一个列表。这与Main
无关,因为论证是passed by value。
我建议使用两种不同的选项之一:
static
变量,并使InitialiseProductList
返回 List<Product>
InitialiseProductList
应该没有参数最重要的是首先要了解为什么现有代码无法正常工作。确保上述所有描述都有意义,并随时提出问题以获得额外的解释。
答案 1 :(得分:1)
可能这项工作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sample
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
public static List<Product> allProducts;
public static void InitialiseMyProducts()
{
allProducts = new List<Product>
{
new Product(){Id=1,Name="TV"},
new Product(){Id=2,Name="Bat"},
new Product(){Id=3,Name="Ball"},
new Product(){Id=4,Name="Chair"},
};
}
public static void Main(string[] args)
{
InitialiseProductList();
foreach (Product res in allProducts)
{
Console.WriteLine("ID:" + " " + res.Id + " " + "Name:" + " " + res.Name);
}
Console.ReadKey();
}
}
}
答案 2 :(得分:0)
public static void Main(string[] args)
{
List<Product> allProducts = InitialiseProductList(allProducts);
foreach (Product res in allProducts)
{
Console.WriteLine("ID:" + " " + res.Id + " " + "Name:" + " " + res.Name);
}
Console.ReadKey();
}