Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 6 MORE ABOUT CLASSES

Properties and Associated Fields

A property is often associated with a field, as shown in the previous two sections. A common practice is to encapsulate a field in a class by declaring it private and declaring a public property to give controlled access to the field from outside the class. The field associated with a property is called the backing field or backing store.

For example, the following code uses the public property MyValue to give controlled access to private field TheRealValue:

class C1

{

private int TheRealValue = 10; public int MyValue

{

set{ TheRealValue = value; } get{ return TheRealValue; }

}

}

//Backing Field: memory allocated

//Property: no memory allocated

//Sets the value of field TheRealValue

//Gets the value of the field

class Program

{

static void Main()

{

Read from the property as if it were a field.

C1 c = new C1(); Console.WriteLine("MyValue: {0}", c.MyValue);

c.MyValue = 20; ← Use assignment to set the value of a property.

Console.WriteLine("MyValue: {0}", c.MyValue);

}

}

125

CHAPTER 6 MORE ABOUT CLASSES

There are several conventions for naming properties and their backing fields. One convention is to use the same string for both names but use camel casing (in which the first letter is lowercase) for the field and Pascal casing for the property. Although this violates the general rule that it is bad practice to have different identifiers that differ only in casing, it has the advantage of tying the two identifiers together in a meaningful way.

Another convention is to use Pascal casing for the property, and then for the field, use the camel case version of the same identifier, with an underscore in front.

The following code shows both conventions:

private

int firstField;

// Camel casing

public

int FirstField

// Pascal casing

{

 

 

get { return firstField; }

 

set { firstField = value; }

 

}

 

 

private

int _secondField;

// Underscore and camel casing

public

int SecondField

 

{

 

 

get { return _secondField; } set { _secondField = value; }

}

126

CHAPTER 6 MORE ABOUT CLASSES

Performing Other Calculations

Property accessors are not limited to just passing values back and forth from an associated backing field; the get and set accessors can perform any, or no, computations. The only action required is that the get accessor return a value of the property type.

For instance, the following example shows a valid (but probably useless) property that just returns the value 5 when its get accessor is called. When the set accessor is called, it doesn’t do anything. The value of implicit parameter value is ignored.

public int Useless

 

 

{

 

 

 

 

 

set{

/*

I'm

not setting anything.

*/

}

get{

/*

I'm

just returning the value 5.

*/

 

return 5;

}

}

The following code shows a more realistic and useful property, where the set accessor performs filtering before setting the associated field. The set accessor sets field TheRealValue to the input value— unless the input value is greater than 100. In that case, it sets TheRealValue to 100.

int TheRealValue = 10;

// The field

int MyValue

// The property

{

 

set

// Sets the value of the field

{

 

TheRealValue = value > 100

// but makes sure it's not > 100

? 100

 

: value;

 

}

 

get

// Gets the value of the field

{

 

return TheRealValue;

 

}

 

}

 

Note In the preceding code sample, the syntax between the equals sign and the end of the statement might look somewhat strange. That expression uses the conditional operator, which will be covered in greater detail in Chapter 8. The conditional operator is a ternary operator that evaluates the expression in front of the question mark, and if the expression evaluates to true, it returns the expression after the question mark. Otherwise, it returns the expression after the colon.

127

CHAPTER 6 MORE ABOUT CLASSES

Read-Only and Write-Only Properties

You can leave one or the other (but not both) of a property’s accessors undefined by omitting its declaration.

A property with only a get accessor is called a read-only property. A read-only property is a safe way of passing an item of data out from a class or class instance without allowing too much access.

A property with only a set accessor is called a write-only property. A write-only property is a safe way of passing an item of data from outside the class to the class without allowing too much access.

At least one of the two accessors must be defined, or the compiler will produce an error message.

Figure 6-10 illustrates read-only and write-only properties.

Figure 6-10. A property can have one or the other of its accessors undefined.

128

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]