C# 从C中的对象列表中获取数据

C# 从C中的对象列表中获取数据,c#,list,C#,List,我想从我的产品列表中获取id、名称和货币:1-TID-13.2 namespace Test { class Product { private int id; private string name; private double currency; List<Product> products = new List<Product>(); public Product(in

我想从我的产品列表中获取id、名称和货币:1-TID-13.2

namespace Test
{
    class Product
    {
        private int id;
        private string name;
        private double currency;
        List<Product> products = new List<Product>();
        public Product(int id,string name,double currency)
        {
            this.id = id;
            this.name = name;
            this.currency = currency;
        }
        public void addProduct(Product product)
        {
            products.Add(product);
        }
        public void listOfProducts()
        {
            foreach (object o in products)
            {
                Console.WriteLine(o);
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product(1, "TID", 13.2);
            p.addProduct(p);
            p.listOfProducts();
        }
    }
}
但当我执行这段代码时,我得到Test.product
有人能告诉我应该如何从列表中获取数据吗?不是列表名,而是输出对象本身,但如果不重写字符串,它只输出类型名。您还将产品强制转换为对象,因此无法使用产品属性。而是使用:

foreach (Product p in products)
{
    Console.WriteLine($"{p.Id} - {p.Name} - {p.Currency}");
}
我使用了公共属性,目前您只有私有字段。因此,请按如下方式编辑您的类:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Currency { get; set; }
    List<Product> Products { get; set; }

    public Product(int id, string name, double currency)
    {
        this.Id = id;
        this.Name = name;
        this.Currency = currency;
        this.Products = new List<Product>();
    }
    // ...
}

您有一些编程问题,而不是在产品列表中循环。您需要理解静态类型和非静态类型之间的区别。静态方法属于类本身。这样,当您在声明之前编写static时,就可以说这个变量或方法是针对类的,而不是针对实例的

代码的另一个问题显然是for循环。您应该迭代产品类型而不是对象,因为对象并没有和产品相同的成员

namespace Test
{
    class Product
    {
        static private List<Product> Products;

        private int id;
        private string name;
        private double currency;

        public Product(int id, string name, double currency)
        {
            this.id = id;
            this.name = name;
            this.currency = currency;
        }

        public static void AddProduct(Product product)
        {
            if (Products == null)
            {
                Products = new List<Product>();
            }
            Products.Add(product);
        }

        public static void GetListOfProducts()
        {
            foreach (Product product in Products)
            {
                Console.WriteLine(String.Format("id:{0} name:{1} currency:{2}", product.id, product.name, product.currency));
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Product p = new Product(1, "TID", 13.2);
            Product.AddProduct(p);
            Product.GetListOfProducts();
        }
    }
}

我想向您展示一些C编程的最佳实践代码。包括的一些功能包括:

具有数量、名称和货币属性的不可变对象产品。如果要存储货币类型值,则货币需要为十进制类型。属性具有命名约定。 通过.EqualsProduct other定义相等比较值,并通过实现IEquatable接口在.NET Framework中使用此方法。 通过.ToString方法将任何产品转换为字符串,并通过.Parsetext静态方法将文本反向解析为产品 从产品的每个实例中删除该列表,因为建议在本地定义该列表的使用位置。 在字典集合中使用产品时,根据最佳实践实现GetHashCode。 最后我有一些测试代码来测试所有这些代码 类定义 测试代码
将对象更改为Product and Console.WriteLineo;到Console.WriteLine${o.id}-{o.name}-{o.currency};您的代码中存在错误理解。在实例中声明产品,以便所有产品都有其自己的products属性。这应该是静态的公共列表产品,虽然这不是对您的问题的回答@İhsantemilçiçek我希望您回答我的问题:产品的每个实例都包含一个列表是没有意义的。我收到这个错误对象不包含id@Saad:yes的定义,正如我在上一句中提到的,您必须提供公共属性,您目前只有不能从外部访问的私有字段。您可以简单地将它们公开,但公共字段很少是一个好主意。将它们封装为属性。很抱歉,但仍然不理解。您能告诉我应该向代码中添加什么吗?我希望这个答案能够说明如何覆盖ToString以及它对代码的影响Writelineitem@Saad发生了什么事。你为什么不接受我的回答,为什么投反对票?
public class Product : IEquatable<Product>
{
    public int ID { get; }
    public string Name { get; }
    public decimal Currency { get; }

    public Product(int id, string name, decimal currency)
    {
        this.ID= id;
        this.Name=name;
        this.Currency=currency;
    }

    /// <summary>
    /// Converts a Product into a string description of itself.
    /// </summary>
    /// <returns>
    /// A <see cref="string"/> of the form <![CDATA["123 - ABC - 3.21"]]> with quantity, name and currency.
    /// </returns>
    public override string ToString() => $"{ID} - {Name} - {Currency}";

    /// <summary>
    /// Parses text into a Product.
    /// </summary>
    /// <param name="description">The description of the Product. Expecting the description 
    /// to be of the form <![CDATA["123 - ABC - 3.21"]]> with quantity, name and currency.</param>
    /// <returns>A new Product or null</returns>
    public static Product Parse(string description)
    {
        string[] parts = description.Split('-');
        if(parts.Length==3)
        {
            if(int.TryParse(parts[0].Trim(), out int id))
            {
                string name = parts[1].Trim();
                if(decimal.TryParse(parts[2].Trim(), out decimal currency))
                {
                    return new Product(id, name, currency);
                }
            }
        }
        return null;
    }

    /// <summary>
    /// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
    /// </summary>
    /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
    public override bool Equals(object obj)
    {
        if(obj is Product product)
        {
            return Equals(product);
        }
        return false;
    }

    /// <summary>
    /// Indicates whether the current object is equal to another object of the same type.
    /// </summary>
    /// <param name="other">A Product to compare with this Product.</param>
    public bool Equals(Product other)
    {
        return other!=null
            && ID==other.ID
            && Name==other.Name
            && Currency==other.Currency;
    }

    public override int GetHashCode()
    {
        int hashCode = 1486216620;
        hashCode=hashCode*-1521134295+ID.GetHashCode();
        hashCode=hashCode*-1521134295+EqualityComparer<string>.Default.GetHashCode(Name);
        hashCode=hashCode*-1521134295+Currency.GetHashCode();
        return hashCode;
    }
}
/// <summary>
/// Code for https://stackoverflow.com/q/53321654/380384
/// </summary>
class Program
{
    static void Main(string[] args)
    {
        var all = new List<Product>();
        all.Add(new Product(1, "TID", 13.2m));
        all.Add(new Product(2, "TJQ", 11.8m));
        all.Add(new Product(3, "UIZ", 15.7m));
        string description = "4 - UYA - 18.4";
        all.Add(Product.Parse(description));

        foreach(Product item in all)
        {
            Console.WriteLine(item);
        }
        //1 - TID - 13.2
        //2 - TJQ - 11.8
        //3 - UIZ - 15.7
        //4 - UYA - 18.4

        if(all[3].ToString().Equals(description))
        {
            Console.WriteLine(@"Product -> String is ok.");
        }
        if(Product.Parse(description).Equals(all[3]))
        {
            Console.Write(@"String -> Product is ok.");
        }
    }
}