5
Assignment
•
Assignment of reference types copies only the reference
–
does not create new object
name
price
shares
ibm
s
Stock ibm = new Stock();
Stock s;
s = ibm;
now refer to
same object
6
Reassignment
•
Reference may be reassigned
–
can refer to different objects at different times
–
not required to stay bound to same object
Stock ibm = new Stock();
Stock sun = new Stock();
Stock s;
s = ibm;
s = sun;
s refers to ibm
s refers to sun
7
Parameters
•
Parameters of reference type pass only reference
–
do not copy object
•
Typical to pass reference by value
–
but can pass ref or out if needed
void Liquidate(Stock s)
{
s.Sell(s.shares);
}
Stock ibm = new Stock();
Liquidate(ibm);
parameter is
reference to
passed object
pass reference
type as parameter
name
price
shares 0
s
ibm
8
compare
references?
Comparison
•
Two possible meanings for reference comparison
–
identity: do the two references refer to the same object?
–
equality: do the objects contain equal data?
name IBM
price 56.0
shares 100
name Sun
price 7.50
shares 200
ibm
sun
compare
data?
9
Identity test
•
Use library method to guarantee identity test with references
–
static method Object.ReferenceEquals
Stock ibm = new Stock();
Stock sun = new Stock();
if (Object.ReferenceEquals(ibm, sun))
false, refer to
different objects
10
operator==
•
Operator== may perform either identity or equality test
–
default behavior is identity test
–
type can customize behavior by overloading operator
Stock ibm = new Stock();
Stock sun = new Stock();
if (ibm == sun)
refer to documentation
of Stock class to
determine behavior
11
Keyword null
•
Assign null to indicate reference does not refer to object
–
invalidates reference
–
does not destroy object
Stock ibm = new Stock();
ibm = null;
invalidate
12
Using null reference
•
Error to use null reference
–
can catch and handle NullReferenceException at runtime
–
can test reference before use and avoid exception
Stock s = null;
s.Buy(50);
error: s is null, runtime
exception generated
Stock s;
if (s != null)
s.Buy(50);
test reference
before use
13
Reference field
•
Common for class to contain reference as field
–
reference only
–
not embedded object
class Point
{
int x;
int y;
}
reference
class Circle
{
Point center;
int radius;
}
Circle c = new Circle();
center
radius
c
14
Reference field initial value
•
Reference fields default to null
Circle c = new Circle();
center null
radius 0
c
center will
be null
Không có nhận xét nào:
Đăng nhận xét