简体   繁体   English

Static 方法在所有实现类型之间共享

[英]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?在 c# 中,如何定义由所有派生/实现类型实现的 static 方法? I know you cannot define a static method within an interface.我知道您不能在接口中定义 static 方法。

Basic premise is like this:基本前提是这样的:

Say for example I have a base class of Organism.例如,我有一个有机体的基础 class。 Derived types would be Human and Dog.派生类型将是 Human 和 Dog。

I want a method which can return to me say the number of legs that a given organism has.我想要一种可以返回给我的方法,告诉我给定生物体的腿数。 So Human would be 2, dog would be 4, etc.所以 Human 是 2,dog 是 4,等等。

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.我可以使这样的方法成为实例方法,但这没有多大意义,因为它对所有 Dog 类型都是相同的方法,对所有 Human 类型都是相同的,等等。

I dont think you are fully understanding OO.我不认为你完全理解 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?如果你有 2 条狗(一只叫lucky),而lucky 被一辆失去一条腿的汽车撞到,会发生什么? With your model the entire species of dogs just lost a leg?有了您的 model,整个品种的狗都失去了一条腿?

But in a better model:但在更好的 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.使用 inheritance,您的派生类应该实现自己的版本,返回适当的值。

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.也就是说,静态类型语言的一个好处是,当您确实需要重新审视一个糟糕的假设时,它会迫使您查看依赖于该假设的所有代码......这是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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