简体   繁体   English

将列表放入类 c#

[英]Putting a list into a class c#

Is it possible to put a list into a class?是否可以将列表放入类中? So for example if I have a class of Person and their properties are Name, Age, Valuables can the Valuables property be a list that holds a Valuable class with properties like ItemName, Cost, Quantity?例如,如果我有一个 Person 类并且它们的属性是 Name、Age、Valuables,那么 Valuables 属性是否可以是一个列表,其中包含一个具有 ItemName、Cost、Quantity 等属性的 Valuable 类?

Yes, absolutely!是的,一点没错!

You would just have你只要

public class Person {
     string Name;
     int Age;
     List<Valuable> Valuables = new List<Valuable>();
}

public class Valuable {
    string ItemName;
    double Cost;
    int Quantity;
}

to use the code, you would then使用代码,然后你会

Person bob = new Person { Name = "Bob", Age = 29 };
Valuable bobsCrystalBall = new Valuable { ItemName = "CrystalBall", Cost = 9.99, Quantity = 1}
bob.Valuables.Add(bobsCrystalBall);

@SomeBody should have specified that you can't do Person.Valuables.Add directly, you have to do that on an instance of that class. @SomeBody 应该指定您不能直接执行Person.Valuables.Add ,您必须在该类的实例上执行此操作。 You create an instance of a class with the keyword new .您可以使用关键字new创建一个类的实例。 Similarly with adding an instance of the class Valuable .与添加类Valuable的实例类似。

public class Person
{
     public string Name {get;set;}
     public int Age {get;set;}
     public List<ValuablesDTO> Valuables {get;set;}

     public  class ValuablesDTO
     {
          public string ItemName {get;set;}
          public decimal Quantity {get;set;}
          public decimal Cost {get;set;}
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM