Конструктор C#, объединяющий в цепочку? (Как сделать это?)

  • можно отобразить команды, которые обычно управляют буферами для управления вкладками, поскольку я сделал с gf в моем .vimrc:

    map gf :tabe 
    

    я уверен, что можно сделать то же с [^

  • , я не думаю, что энергия поддерживает это для вкладок (все же). Я использую gt и gT для перемещения в следующие и предыдущие вкладки, соответственно. Можно также использовать Ngt, где N является числом вкладки. Одна обида, которую я имею, - то, что по умолчанию число вкладки не отображено в строке вкладки. Для фиксации этого я поместил пару функций в конце мой .vimrc файл (я не вставлял здесь, потому что это длинно и не отформатировало правильно).

210
задан John Saunders 14 February 2013 в 16:42
поделиться

3 ответа

Вы используете стандартный синтаксис (используя this как метод) для выбора перегрузки, внутри класса:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

затем:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Также обратите внимание:

  • вы можете связать конструкторы с базовым типом, используя base (...)
  • , вы можете поместить дополнительный код в каждый конструктор
  • по умолчанию (если вы ничего не укажете ) is base ()

Для «почему?»:

  • сокращение кода (всегда хорошо)
  • необходимо для вызова нестандартного конструктора базы, например:

     SomeBaseType (int id): base (id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };
324
ответ дан 23 November 2019 в 04:35
поделиться

This is best illustrated with an example. Imaging we have a class Person

public Person(string name) : this(name, string.Empty)
{
}

public Person(string name, string address) : this(name, address, string.Empty)
{
}

public Person(string name, string address, string postcode)
{
    this.Name = name;
    this.Address = address;
    this.Postcode = postcode;
}

So here we have a constructor which sets some properties, and uses constructor chaining to allow you to create the object with just a name, or just a name and address. If you create an instance with just a name this will send a default value, string.Empty through to the name and address, which then sends a default value for Postcode through to the final constructor.

In doing so you're reducing the amount of code you've written. Only one constructor actually has code in it, you're not repeating yourself, so, for example, if you change Name from a property to an internal field you need only change one constructor - if you'd set that property in all three constructors that would be three places to change it.

29
ответ дан 23 November 2019 в 04:35
поделиться

Are you asking about this?

  public class VariantDate {
    public int day;
    public int month;
    public int year;

    public VariantDate(int day) : this(day, 1) {}

    public VariantDate(int day, int month) : this(day, month,1900){}

    public VariantDate(int day, int month, int year){
    this.day=day;
    this.month=month;
    this.year=year;
    }

}
6
ответ дан 23 November 2019 в 04:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: