Implementace zjednodušené třídy s automaticky implementovanými vlastnostmi (Průvodce programováním v C#)

Tento příklad ukazuje, jak vytvořit neměnnou odlehčenou třídu, která slouží pouze k zapouzdření sady automaticky implementovaných vlastností. Tento druh konstruktoru použijte místo struktury, pokud je nutné použít sémantiku typu odkazu.

Neměnnou vlastnost můžete nastavit následujícími způsoby:

  • Deklarujte pouze přístupový objekt get , díky kterému je vlastnost neměnná všude s výjimkou konstruktoru typu.
  • Deklarujte inicializační objekt místo přístupového objektuset, který vlastnost nastaví pouze v konstruktoru nebo pomocí inicializátoru objektů.
  • Deklarujte, že objekt set je privátní. Vlastnost je nastavena v rámci typu, ale je neměnná pro uživatele.

Do deklarace vlastnosti můžete přidat required modifikátor, který volajícím vynutí nastavit vlastnost jako součást inicializace nového objektu.

Následující příklad ukazuje, jak se vlastnost s pouze get accessors liší než jeden s get a private set.

class Contact
{
    public string Name { get; }
    public string Address { get; private set; }

    public Contact(string contactName, string contactAddress)
    {
        // Both properties are accessible in the constructor.
        Name = contactName;
        Address = contactAddress;
    }

    // Name isn't assignable here. This will generate a compile error.
    //public void ChangeName(string newName) => Name = newName;

    // Address is assignable here.
    public void ChangeAddress(string newAddress) => Address = newAddress;
}

Příklad

Následující příklad ukazuje dva způsoby implementace neměnné třídy, která má automaticky implementované vlastnosti. Každý způsob deklaruje jednu z vlastností s privátní set a jednou z vlastností pouze.get První třída používá konstruktor pouze k inicializaci vlastností a druhá třída používá statickou metodu továrny, která volá konstruktor.

// This class is immutable. After an object is created,
// it cannot be modified from outside the class. It uses a
// constructor to initialize its properties.
class Contact
{
    // Read-only property.
    public string Name { get; }

    // Read-write property with a private set accessor.
    public string Address { get; private set; }

    // Public constructor.
    public Contact(string contactName, string contactAddress)
    {
        Name = contactName;
        Address = contactAddress;
    }
}

// This class is immutable. After an object is created,
// it cannot be modified from outside the class. It uses a
// static method and private constructor to initialize its properties.
public class Contact2
{
    // Read-write property with a private set accessor.
    public string Name { get; private set; }

    // Read-only property.
    public string Address { get; }

    // Private constructor.
    private Contact2(string contactName, string contactAddress)
    {
        Name = contactName;
        Address = contactAddress;
    }

    // Public factory method.
    public static Contact2 CreateContact(string name, string address)
    {
        return new Contact2(name, address);
    }
}

public class Program
{
    static void Main()
    {
        // Some simple data sources.
        string[] names = ["Terry Adams","Fadi Fakhouri", "Hanying Feng",
                            "Cesar Garcia", "Debra Garcia"];
        string[] addresses = ["123 Main St.", "345 Cypress Ave.", "678 1st Ave",
                                "12 108th St.", "89 E. 42nd St."];

        // Simple query to demonstrate object creation in select clause.
        // Create Contact objects by using a constructor.
        var query1 = from i in Enumerable.Range(0, 5)
                    select new Contact(names[i], addresses[i]);

        // List elements cannot be modified by client code.
        var list = query1.ToList();
        foreach (var contact in list)
        {
            Console.WriteLine("{0}, {1}", contact.Name, contact.Address);
        }

        // Create Contact2 objects by using a static factory method.
        var query2 = from i in Enumerable.Range(0, 5)
                        select Contact2.CreateContact(names[i], addresses[i]);

        // Console output is identical to query1.
        var list2 = query2.ToList();

        // List elements cannot be modified by client code.
        // CS0272:
        // list2[0].Name = "Eugene Zabokritski";
    }
}

/* Output:
    Terry Adams, 123 Main St.
    Fadi Fakhouri, 345 Cypress Ave.
    Hanying Feng, 678 1st Ave
    Cesar Garcia, 12 108th St.
    Debra Garcia, 89 E. 42nd St.
*/

Kompilátor vytvoří záložní pole pro každou automaticky implementovanou vlastnost. Pole nejsou přístupná přímo ze zdrojového kódu.

Viz také