Not sure when to use an abstract property and when not

后端 未结 5 1137
野性不改
野性不改 2020-12-04 12:52

I\'m not really sure what looks better or when do I really use in abstract classes and properties, or when to use non abstract properties. I\'ll try to make a simple example

5条回答
  •  失恋的感觉
    2020-12-04 13:59

    Abstract members are simply virtual members that you have to override. You use this for something that has to be implemented, but can't be implemented in the base class.

    If you want to make a virtual property, and want that it has to be overridden in the class that inherits your class, then you would make it an abstract property.

    If you for example have an animal class, its ability to breathe would not be possible to detemine just from the information that it's an animal, but it's something that is pretty crucial:

    public abstract class Animal {
    
      public abstract bool CanBreathe { get; }
    
    }
    

    For a fish and a dog the implementation would be different:

    public class Dog : Animal {
    
       public override bool CanBreathe { get { return !IsUnderWater; } }
    
    }
    
    public class Fish : Animal {
    
       public override bool CanBreathe { get { return IsUnderWater; } }
    
    }
    

提交回复
热议问题