Class structure for list class?

I am looking for some help in class structure. Suppose I have a class called "Dog" that contains information about the dog (name, weight, type), but because there can be several dogs, I would also like the class to keep all these dogs for use throughout my project. What is the best way to do this?

Just to have a DogList class that stores information about the Dog class in a public list? Let me get it on my own?

Or should the list be static in the original dog class? maybe in the constructor, when someone creates a new dog, the dog gets on the static list?

Edit: Sorry, the question was a little missed. Here is the structure that I still have, wondering if there is a better way to implement it.

public class Dog
{
    public string name{get;set;}
    public int weight { get; set; }
}

public class DogFactory //not sure if thats the correct wording
{
    public List<dog> lstDogs = new List<dog>();
    public void setDogs()
    {
    Animal.Retrieve("Dog"); 
    //will retrieve a list of all dogs, with details, though this is costly to use
        foreach(Animal.Dog pet in Animal._Dogs)
        {
            Dog doggie = new doggie();
            doggie.Name = pet.Name;
            ...etc
            lstDog.add(doggie);
        }
    }
}
+5
source share
3 answers

The easiest way to make a list of dogs:

List<Dog>

This is a strongly typed list of Dogs using a class List<T>from System.Collections.Generic. You can make a class of this:

public class DogList : List<Dog>

Although this is usually not required if you do not want to add properties specifically to the Dogs list, and not to the dogs themselves.

UPDATE:

Usually you do not need to create a dedicated list class when using List<T>. In most cases, you can do this:

public class DogService
{
    public List<Dog> GetAllDogs()
    {
        var r = new Repository(); // Your data repository
        return r.Dogs.ToList();   // assuming your repository exposes a 'Dogs query'
    }
}

LINQ , ToList() List<T>, , List<T>.

+5

, # List<>, , , DogList. , . , private, . , factory ( ).

+3

? , , , - , ?

, .

*: , Dog , ? , Dog?

, , , . , , , , - , .

* .

+1
source

All Articles