如何在c#中使用多态(normaly和Abstract)

时间:2016-11-09 12:56:58

标签: c# polymorphism abstract

我理解如何在类中使用多态函数并覆盖。 我不明白的是如何将它用于对象。

abstract class Film
{
    protected string film_name;

    public Film(string film_name)
    {
        this.film_name = film_name;
    }

    public string GetFilmName()
    {
        return this.film_name;
    }



}

class Siries : Film
{
    private int season_number;

    public Siries
    {
        // What do i need to write here? and why?..
    }


}

3 个答案:

答案 0 :(得分:0)

如果Siries是一部特定的电影。

关键字" base"调用基类的构造函数" Film"。

public Siries() : base("siries")
{
}

如果你想用名字和数字制作系列,你必须这样做。

public Siries(string siries_name, int season_number) : base(siries_name)
{
    this.season_number = season_number;
}

答案 1 :(得分:0)

可能可以回答你的期望。

只需创建一个指向派生类的基类对象。这是继承的概念。

根据你的例子,

Film f = new Siries();
f.method()// Method what you expect to call by object

答案 2 :(得分:0)

我建议使用属性而不是Get函数重新设计;至于你在派生类构造函数中的问题,你应该实现

  • 调用适当的基类构造函数
  • 添加派生类逻辑

类似的东西:

  abstract class Film {
    // let field be private, but property be protected 
    private string m_FilmName;

    public Film(string filmName) {
      FilmName = filmName;
    }

    // FilmNam is more natural/readable in your case than GetFilmName() method
    public string FilmName {
      get {
        return m_FilmName;
      }
      protected set { // "private set" seems to be a better choice
        // do not forget to validate the input value in public/protected methods
        if (string.IsNullOrWhiteSpace(value))
          throw new ArgumentNullException("value", 
            "FileName must not be null or white space");

        m_FilmName = value;
      }
    }
  }

...

  class Siries: Film {
    private int m_SeasonNumber;

    // Answer: 
    //   1. You have to call base class constructor ": base(filmName)"
    //   2. Add up some logic with "seasonNumber" - "SeasonNumber = seasonNumber;"
    public Siries(String filmName, int seasonNumber = 1)
      : base(filmName) {

      SeasonNumber = seasonNumber;
    }

    public int SeasonNumber {
      get {
        return m_SeasonNumber;
      } 
      protected set { // may be "private set" or just "set" (public)
        // do not forget to validate the input value in public/protected methods
        if (value <= 0)
          throw new ArgumentOutOfRange("value", "SeasonNumber must be positive");

        m_SeasonNumber = value;
      }
    }
  }