开发者

Static Method Shared Among all Implementing Types

In c# how can one define a static method that is to implemented by all derived/implementing types? I know you cannot define a static method within an interface.

Basic premise is like this:

Say for example I have a base class of Organism. Derived types would be Human and Dog.

I want a method which can return to me say the number of legs that a give开发者_运维问答n organism has. So Human would be 2, dog would be 4, etc.

I can make such a method an instance method, but it doesn't make much sense because its going to be the same method for all Dog types, and the same for all Human types, etc.


I dont think you are fully understanding OO. It makes perfect sense to make it an instance method.

What would happen if you have 2 dogs(one named lucky), and lucky gets hit by a car losing a leg? With your model the entire species of dogs just lost a leg?

But in a better model:

#psudo 
class Organism{
   public abstract void legs(){ return 0;}
}
class Dog : Organism{
   private int _legs;
   public int legs(){ return _legs; }
}

then lucky would just lose a leg.



Make it an instance method. Using inheritance, your derived classes should implement their own versions that return the appropriate values.


Something like this.

abstract class Organism
{
    public abstract int NumberOfLegs();
}

abstract class Biped : Organism
{
    public sealed override int NumberOfLegs()
    {
        return 2;
    }
}


abstract class Quadroped : Organism
{
    public sealed override int NumberOfLegs()
    {
        return 4;
    }
}

class Humand : Biped
{

}



class Dog : Quadroped
{

}

But I'd be worried about using such a taxonomy and even more worried about baking in those kinds of assumptions. That said, one nice thing about statically typed languages is that when you do need to revisit a bad assumption, it forces you to look at all the code relying on that assumption... this is a good thing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜