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

时间:2018-11-15 14:29:16

标签: 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(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 有人可以告诉我应该从列表而不是列表名称中获取数据

3 个答案:

答案 0 :(得分:0)

您可以输出对象本身,但是如果不覆盖ToString,则仅输出类型名称。您还将Product强制转换为Object,因此将无法使用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>();
    }
    // ...
}

答案 1 :(得分:0)

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

  • 具有属性ProductQuantityName的不可变对象Currency。如果要存储货币类型值,则货币必须为decimal类型。属性具有PascalCase命名约定。
  • 通过.Equals(Product other)定义比较值的相等性,并通过实现IEquatable<Product>接口在.NET Framework中使用此方法。
  • 通过Product方法将任何string转换为.ToString(),并通过Product静态方法将文本反向解析为.Parse(text) < / li>
  • 从产品的每个单个实例内部删除了List<Product>,因为建议在要使用该产品的位置进行本地定义。
  • GetHashCode()集合中使用Product时,按照最佳做法实施Dictionary
  • 最后我有一些测试代码可以测试所有这些代码

类定义

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.");
        }
    }
}

答案 2 :(得分:-1)

您遇到了一些程序问题,而不是遍历产品列表。您需要了解静态类型和非静态类型之间的区别。静态方法属于该类本身。这样一来,当您在声明前写static时就说该变量或方法是用于类而不是实例的。

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

der-der2