public Object getDog() {
.......
if (noDogsFound) {
return null;
}
}
....
Dog dog = (Dog) getDog(); // casting a null object to type Dog
if (dog != null) {
...dosomething();
}
enum Animal {DOG, CAT, INT, LONG};
Dod d = (dog)getObject(DOG); // guaranteed to return a dog but may also return null
Cat c = (Cat) getObject(CAT);
int i = (int) getObject(INT); // returns 0 and not null so this isn't an issue
我想这没什么大不了的
C#:
object o = getObject(DOG);
if (o!=null) {d = (Dog)o;}
else {d = null}
var result = GetObject();
Dog d;
Cat c;
if (result == null)
{
// There is not object.
return;
}
d = result as Dog;
if (d != null)
{
// The object is a Dog instance;
return;
}
c = result as Cat;
if (c != null)
{
// The object is a Cat instance;
return;
}