不使用虚拟关键字的多态性

时间:2016-05-27 07:30:10

标签: c# polymorphism

显然使用虚拟和覆盖是正常情况,但是这个电信的例子是否算数?

public class Pipe
{
  // whole bunch of protected member variables such as bandwidth, latency, download limit 
  // etc,

  public int GetCost()
  {
     // work out cost based on above
  }
}

public class BigFatPipe : Pipe
{
  public BigFatPipe()
  {
    // sets up the member variables one way
  }
}

public class CheapestPossiblePipe: Pipe
{
  public CheapestPossiblePipe()
  {
    // sets up the member variables another way
  }
}

然后你可以打电话给

PrintPrice(new BigFatPipe())

PrintPrice(new CheapestPossiblePipe())

public void PrintPrice(Pipe pipe)
{
   int a = pipe.GetCost();
   ....
}

你会得到两个不同的答案。这不是最有用的例子,但它算不算?

4 个答案:

答案 0 :(得分:0)

这个post here对于多态性究竟是什么有一个有用的讨论。

我认为大多数定义都没有明确声明对象必须具有多态的虚函数 - 所以是的,我认为你的例子很重要。

答案 1 :(得分:0)

构造函数重载是实现静态多态的公认方法。虽然这不是真正的构造函数重载,但它已经接近了。所以,是的,我称之为多态性。

答案 2 :(得分:0)

这种模式确实有效,但引入一堆类会使用户无用地混淆:他们会想知道这些类的做法有多么不同。

一些工厂方法将完成同样的工作,并且更容易理解和维护:

public class Pipe
{
  // whole bunch of private member variables such as bandwidth, latency, download limit 
  // etc,

  public int GetCost()
  {
     // work out cost based on above
  }

  public static Pipe MakeBigFatPipe()
  {
      var result = new Pipe();
      // sets up the member variables one way
      return result;
  }

  public static Pipe MakeCheapestPossiblePipe()
  {
      var result = new Pipe();
      // sets up the member variables another way
      return result;
  }
}

答案 3 :(得分:-1)

如果我是你,我会使用以下方法:

public interface IGetCost
{
    int GetCost();
}

public class Pipe : IGetCost
{
    public int GetCost(){}
}

public class BigFatPipe : IGetCost
{
    //aggregation
    private readonly Pipe _pipe;

    public BigFatPipe(Pipe pipe)
    {
        _pipe = pipe;
    }
    public int GetCost() { }
}

public class CheapestPossiblePipe : IGetCost
{
    private readonly Pipe _pipe;

    public CheapestPossiblePipe(Pipe pipe)
    {
        _pipe = pipe;
    }
    public int GetCost() { }
}

public static void PrintPrice(IGetCost obj)
{
    int cost = obj.GetCost();
    Console.WriteLine(cost);
}

static void Main(string[] args)
{
    IGetCost p;

    p = new Pipe();
    PrintPrice(p);

    p = new BigFatPipe();
    PrintPrice(p);

    p = new CheapestPossiblePipe();
    PrintPrice(p);
}

我还需要说两个不同的东西 - 多态和重载

多态性

public class foo
{
    public virtual void foo1{/*....*/}
}

public class fooA : foo
{
    public override void foo1{/*....*/}
}

public class fooB : foo
{
    public new void foo1{/*....*/}
}

public class fooC : foo
{
    //new is the default modifier
    public void foo1{/*....*/}
}

过载

public class foo{
    public int foo1{/*....*/}
    public int foo1(int a){/*....*/}
    public int foo1(string a){/*....*/}
    public int foo1(int a, string b){/*....*/}
}