Используя это () в Конструкторах C#

С другим примером как

Перечислите таблицу

    id: SERIAL
    name: TEXT
    enumerate_id: INT

Все родители, у которых есть дети (все ветви дерева, даже корни, но без листьев!)

SELECT id, name, enumerate_id
FROM enumerate p
WHERE EXISTS (
    SELECT 1 FROM enumerate c
    WHERE c.enumerate_id = p.id
);

Все дети, у которых нет детей (все листья дерева)

SELECT id, name, enumerate_id
FROM enumerate p
WHERE NOT EXISTS (
    SELECT 1 FROM enumerate c
    WHERE c.enumerate_id = p.id
);

Обратите внимание, что единственный, кто меняется, это NOT EXISTS

Надеюсь, это поможет

10
задан Tim 14 December 2009 в 14:44
поделиться

3 ответа

  • Example 1 is valid (assuming there is a parameterless constructor), and calls the parameterless constructor as part of initialization. See my article on constructor chaining for more details. EDIT: Note that since the OP's edit, it's infinitely recursive.
  • Example 2 is never valid
  • Example 3 is only valid when Foo is a struct, and doesn't do anything useful.

I would steer clear of assigning to this in structs. As you can see from the other answers, the very possibility of it is fairly rarely known (I only know because of some weird situation where it turned up in the spec). Where you've got it, it doesn't do any good - and in other places it's likely to be mutating the struct, which is not a good idea. Structs should always be immutable :)

EDIT: Just to make people go "meep!" a little - assigning to this isn't quite the same as just chaining to another constructor, as you can do it in methods too:

using System;

public struct Foo
{
    // Readonly, so must be immutable, right?
    public readonly string x;

    public Foo(string x)
    {
        this.x = x;
    }

    public void EvilEvilEvil()
    {
        this = new Foo();
    }
}

public class Test
{
    static void Main()
    {
        Foo foo = new Foo("Test");
        Console.WriteLine(foo.x); // Prints "Test"
        foo.EvilEvilEvil();
        Console.WriteLine(foo.x); // Prints nothing
    }
}
32
ответ дан 3 December 2019 в 13:30
поделиться

Examples 2 and 3 are not legal C#.

EDIT: Jon points out accurately that 3 is legal when Foo is a struct. Go check out his answer!

11
ответ дан 3 December 2019 в 13:30
поделиться

No they will not because only the first constructor is actually legal. The other two are illegal for various reasons.

EDIT Interesting, 3 is indeed legal when Foo is a struct. But even in that case, it is a redundant assignment.

4
ответ дан 3 December 2019 в 13:30
поделиться
Другие вопросы по тегам:

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