[英]List not getting initialized c#
對於下面的以下代碼,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();
}
}
}
您有幾個變量都稱為allProducts
:
InitialiseMyProducts
的參數 Main
的局部變量 您要在Main
初始化兩次局部變量,然后將其傳遞給InitialiseMyProducts
(或InitialiseProductList
您已將名稱更改了一半)。 但是,該方法然后忽略先前的值,並更改參數以引用另一個列表。 這與Main
無關,因為參數已按值傳遞 。
我建議兩個單獨的選擇之一:
static
變量,並使InitialiseProductList
返回一個List<Product>
InitialiseProductList
應該沒有參數 最重要的是首先要理解為什么現有代碼無法正常工作。 確保上面的所有描述都是合理的,並隨時提出問題進行進一步的解釋。
可能是這項工作
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();
}
}
}
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.