czwartek, 26 lutego 2015

Cz2 zmagań z C# - base oraz this (w konstruktorach)...

CD mojego pamiętnika zmagań z C#. Najprostrze objaśnienia znalazłem na stronach dotnetperls:
base w konstruktorach - odwołanie do konstruktora parenta.
public class A // To jest moja klasa bazowa (base).
{
    public A(int value)
    {
 Console.WriteLine("Klasa base A()");
    }
}

public class B : A // Ta klasa dziedziczy z klasy A,
{
    public B(int value)
 : base(value)
    {
 // najpierw wywoływany jest konstruktor bazy.
 // ... następnie wykonany jest konstruktor B
 Console.WriteLine("Pochodna klasa B()");
    }
}

class Program
{
    static void Main()
    {
 // Tworzy nową instancję/wystąpienie klasy  A, klasy bazowej.
 // ... następnie wywołuje klasę B, która wykona konstruktor bazy.
 A a = new A(0);
 B b = new B(1);
    }

Przykład z Video Pragim Technologies:
public class ParentClass
{
    public ParentClass()
    {
      Console.WriteLine(”ParentCass Constructor caI1ed");
    )
    public ParentClass(string Message) //TEN KONSTRUKTOR ZOSTANIE WYWOŁANY
    {
      Console.WriteLine(Message);
    )
}
public class ChildClass : ParentClass
(
    public ChildClass() : base(”Derived class controlling Parent class”) //UWAGA "base"
    (
    Console.WriteLine(”ChildClass Constructor called”);
    )
}
public class Program
(
    public static void Mamo
    (
       ChildClass CC = new ChildClass;
    }

} 
Rezultat: Derived class controlling Parent class.
ChildClass Constructor called. A teraz keyword this... pozwala konstruktorom odwoływać się do konstruktorów tej samej klasy. Przykład z dotnetperls:
using System;

class Mouse
{
    public Mouse()
 : this(-1, "")
    {
 // Ten pierwszy konstruktor wywoła drugi konstruktor z parametrami (-1, "").
    }

    public Mouse(int weight, string name)
    {
 // Constructor implementation.
 Console.WriteLine("Constructor weight = {0}, name = {1}",
     weight,
     name);
    }
}

class Program
{
    static void Main()
    {
 
 Mouse mouse1 = new Mouse();
 Mouse mouse2 = new Mouse(10, "Sam");
    }
}

Rezultat

Constructor weight = -1, name =
Constructor weight = 10, name = Sam


Brak komentarzy:

Prześlij komentarz