开发者

C# Property reference type?

I'm starting out in C# and I have a question.

Say I have an object:

Person

and a property on Person called Cat:

Person.Cat

If I do:

Cat cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;

Is Cat a direct re开发者_如何学运维ference to cat? If I do:

Person.Cat.Name = "John";

Will cat's Name be "John"?

Because I think I tried doing something like this before, and I got NullReferenceException or something like that.


If 'cat' is a class, i.e., a reference type, than a copy of that reference will be stored in person.Cat. That means that changes made to properties of 'cat' will be reflected in person.Cat. However, since it is a copy of the original reference, the behavior is like so:

Cat cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;
cat.Name = "Will";  //Person.Cat.Name is now "Will"
cat = new Cat(stuff);
cat.Name = "Greg";  
// Person.Cat is still named "Will".  
// The original reference now points  to a different object on the heap than does Person.Cat.

if Cat is a value type, then a copy is made upon assignment and changes in one will not reflect in the other (of course, a struct could have a reference type property or public field, but you get the idea).


This is correct, assuming your full code is something like this:

// Person class.
public class Person {

    // Automatic property.
    public Cat Cat { get; set; }

}

// Cat class (not a struct!).
public class Cat {

    // Automatic property.
    public string Name { get; set; }

}

In this case, accessing myPerson.Cat will give you a direct reference to that object. You can call methods on it, access its properties, pass it into a method that accepts a Cat parameter, whatever you like.

However, in this situation you have no certainty that the myPerson.Cat property is not null. Any code could set it to be any object of type Cat, or null. If something has set it to null and you try to access myPerson.Cat.Name, you will get a NullReferenceException.

In order to avoid getting those exceptions, you should always verify that the property is not null through an explicit check like if (myPerson.Cat != null) { ... } before using it. You can skip this step if you know for sure that it can never be null, and that nothing can violate this assumption. You may want to look into using code contracts to ensure this in the future when you're more comfortable with the language.


Is Cat a direct reference to cat?

Yes. For example:

var cat = new Cat(stuff);
cat.Name = "Alan";
Person.Cat = cat;
cat.Name = "George";
var nowCalledGeorge = Person.Cat.Name;

So the answer to this question

Will cat's Name be "John"?

is yes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜