Accept method parameters from the constructor

I have several classes that require a lot of parameters. I just created an example with two parameters to demonstrate my problem.

public class Zoo
{
    public List<Animal> Animals { get; set; }

    public Zoo()
    {
        Animals = new List<Animal>();
    }

    // Pass all parameters
    public void AddAnimal(string name, int age)
    {
        Animals.Add(new Animal(name, age));
    }

    // -> pseudo code <- Create the parameter reference automated -> pseudo code <-
    public void AddAnimal(params ...)
    {
        Animals.Add(new Animal(...));
    }
}

public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Animal(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

If I want to add Animalto mine Zoo, I have 2 options.

  • Pass all parameters to the method AddAnimal
  • Add object AnimaltoList

As I said, I have many parameters and many "animals".

Is it possible to refer to constructor parameters Animalwithout manually adding them to the AddAnimal method? (See: -> pseudo code <-in the first block of code)

But I want to save a method call.

Zoo zoo = new Zoo();
zoo.AddAnimal("Tom", 8);

Thanks in advance, Yang

Edit: For some reason, I want to prevent using one of the following methods:

zoo.AddAnimal(new Animal("Ben", 9));
zoo.AddAnimal(new Animal { "Ben", 9 }); // With empty constructor...

, : c & p ?

+3
2

, . :

public void Add(Animal animal)
{
    if(animal == null) throw new ArgumentNullException("animal");
    Animals.Add(animal);
}
...
zoo.Add(new Animal("Fred", 27));

/ / " ".

+5

, :

public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return "[" + Name + ", " + Age + "]";
    }
}

public class Zoo
{
    public List<Animal> Animals { get; set; }

    public Zoo()
    {
        Animals = new List<Animal>();
    }

    // Pass all parameters
    public void AddAnimal(string name, int age)
    {
        Animal animal = new Animal
        {
            Name = name,
            Age = age
        };

        Animals.Add(animal);
    }

    // -> pseudo code <- Create the parameter reference automated -> pseudo code <-
    public void AddAnimal(params object[] animalProperties)
    {
        Animal animal = new Animal
        {
            Name = animalProperties[0] as string,
            Age = (animalProperties[1] as int?).Value
        };

        Animals.Add(animal);
    }
}

public class Example
{
    public void Run()
    {
        Zoo zoo = new Zoo();
        zoo.AddAnimal("Tom", 8);

        foreach (Animal a in zoo.Animals)
        {
            Console.WriteLine(a.ToString());
        }
    }
}

, , - , , , , ( , , )

: , , . , , (, ).

+1

All Articles