Answer the question
In order to leave comments, you need to log in
How to make multiple variables on request?
I don't understand how to write something like this: var s = new Test("a", "b", "c");
It seems to be done through params, but how can I write it down so that I can access it?
Here is my class:
public class Test
{
private List<string> _elements = new List<string>();
public void AddElement(string x)
{
string AddElement = x;
_elements.Add(AddElement);
Console.WriteLine($"Элемент <{AddElement}> добавлен.");
Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
Console.WriteLine();
}
}
Answer the question
In order to leave comments, you need to log in
There are two ways:
public class Test
{
public Test(params string[] elements) {
foreach(var element in elements)
AddElement(element);
}
private List<string> _elements = new List<string>();
public void AddElement(string x)
{
string AddElement = x;
_elements.Add(AddElement);
Console.WriteLine($"Элемент <{AddElement}> добавлен.");
Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
Console.WriteLine();
}
}
var x = new Test("a", "b", "c");
public class Test
{
private List<string> _elements = new List<string>();
// Для Collection Initializer нужен публичный метод Add
public void Add(string element) => AddElement(element);
public void AddElement(string x)
{
string AddElement = x;
_elements.Add(AddElement);
Console.WriteLine($"Элемент <{AddElement}> добавлен.");
Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
Console.WriteLine();
}
}
var x = new Test { "a", "b", "c" };
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question