简体   繁体   中英

Using properties of a class on a generic object

essentially what I am trying to do is the following : I have a class called Animals that reads some animals that has several properties associate with it such as age,type,birth date etc. What I'm facing problem with is the CompareTo() method which takes a generic object as a parameter, checks if it's of the type Animal and if so compares the name associated with this object to the instance of the name associate with the instance of the Animal.

I tried using

this.Name.CompareTo(object.Name);

but obviously it doesn't work for this case since Name isn't defined within object.Is there a way around this ? Being able to compare properties inside an object, knowing that it is of type Animal, to properties within an instance of the Animal class ? Thanks in advance.

You can use the as operator to cast the object to an Animal . If the cast succeeded, then you can compare the name properties. If the cast failed, the object will be null (and you normally return 1 if the other object is null).

public int CompareTo(object obj)
{
    var other = obj as Animal;

    if (other == null) { return 1; }
    if (this.Name == null) return (other.Name == null) ? 0 : -1;
    return this.Name.CompareTo(other.Name);
}

You need to cast the object to an Animal before comparing the names:

public int CompareTo(object obj)
{
    if (obj == null)
    {
        return 1;
    }

    if (obj is Animal)
    {
        Animal other = (Animal)obj;
        return this.Name.CompareTo(other.Name);
    }

    return 1;  // or whatever behavior you want if obj is not an Animal
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM