簡體   English   中英

列表未初始化C#

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM