logo
CSharp_Prog_Guide

Примечания

Обратите внимание, что при замене объявления new private string Id new public string Id, результат будет следующим:

Name and ID in the base class: Name-BaseClass, ID-BaseClass

Name and ID in the derived class: John, John123

How to: Declare and Use Read/Write Properties

Properties provide the convenience of public data members without the risks that come with unprotected, uncontrolled, and unverified access to an object's data. This is accomplished through accessors: special methods that assign and retrieve values from the underlying data member. The set accessor enables data members to be assigned, and the get accessor retrieves data member values.

This sample shows a Person class that has two properties: Name (string) and Age (int). Both properties provide get and set accessors, so they are considered read/write properties.

Example

class Person

{

private string m_name = "N/A";

private int m_Age = 0;

// Declare a Name property of type string:

public string Name

{

get

{

return m_name;

}

set

{

m_name = value;

}

}

// Declare an Age property of type int:

public int Age

{

get

{

return m_Age;

}

set

{

m_Age = value;

}

}

public override string ToString()

{

return "Name = " + Name + ", Age = " + Age;

}

}