【问题标题】:How do i overload a constuctor method so i don't have to provide a value for it [duplicate]我如何重载构造函数方法,所以我不必为它提供值[重复]
【发布时间】:2019-06-28 07:57:36
【问题描述】:

我在网上去了很多地方,但找不到任何可以很好地解释重载构造函数的东西。我只是在寻找一些指导

我必须在我的歌曲类中重载构造函数,以允许创建歌曲而不为 copySold 提供值。

class Song
{
    string name;
    string artist;
    int copiesSold;

    public Song(string name, string artist, int copiesSold)
    {
        this.name = name;
        this.artist = artist;
        this.copiesSold = copiesSold;
    }

    public Song()
    {
    }

    public string GetArtist()
    {
        return artist;
    }

    public string GetDetails()
    {
        return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},";
    }

    public string GetCertification()
    {
        if (copiesSold < 200000)
        {
            return null;
        }
        if (copiesSold < 400000)
        {
            return "Silver";
        }
        if (copiesSold < 600000)
        {
            return "Gold";
        }
        return "Platinum";

【问题讨论】:

  • 您在寻找public Song(string name, string artist) : this(name, artist, 0) {}吗?

标签: c# methods constructor overloading


【解决方案1】:

同一个类的构造函数的调用必须通过this关键字来执行,如下例所示

class Song
{
   public string name;
    string artist;
    int copiesSold;

    public Song(string name, string artist, int copiesSold)
    {
        this.name = name;
        this.artist = artist;
        this.copiesSold = copiesSold;
    }

    public Song():this("my_name","my_artist",1000)
    {
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多