无法弄清楚这个c#参考

时间:2014-11-13 04:30:51

标签: c#

我正在使用"这个"我的默认构造函数中的关键字,下面是类电影中的代码

namespace Movie_List
{ enum GenreType { Action, War, Drama, Thriller }; 
 class Movie 
 { 
    //Data Members 
    private String _title; 
    private int _rating; 
    private GenreType _type;

    //Properties


    public GenreType GenType
    {
        get { return _type; }
        set { _type = value; }
    }
    public String Title
    {
        get { return _title; }
        set { _title = value; }
    }


    public int Rating
    {
        get { return _rating; }
        set { _rating = value; }
    }




    public Movie()
        : this("Jaws", GenreType.Action, 4) { } 

    public Movie(String title, GenreType type, int rating ) //working ctor
    {
        Title = title;
        GenType = type;
        Rating = rating;

    }

    public override string ToString()
    {           
        return String.Format(" {0} Genre : {1},  Rating: {2:d} Stars. ", Title, GenType, Rating);
    }

}

我想从文本文件中读取,所以我在MainWindow.xaml.cs中使用了这段代码

private void btnLoad_Click(object sender, RoutedEventArgs e)
{

    string lineIn = "";
    string[] filmarray;
    using (StreamReader file = new StreamReader("filmlist.txt"))
    {
        while ((lineIn = file.ReadLine()) != null)
        {
            filmarray = lineIn.Split(new char[] { ',' });
            moviecollection.Add(new Movie()

            {
                Title = filmarray[0],
                GenType = (GenreType)Enum.Parse(typeof(GenreType), filmarray[1]),
                Rating = Convert.ToInt32(filmarray[2]),
            });
            lstFilms.ItemsSource = moviecollection;
        }


    }
}

我现在不需要这段代码

: this("Jaws", GenreType.Action, 4)

但是当我删除它时,类型动作和评级0星仍然会打印。

为什么这个发生有人知道?

2 个答案:

答案 0 :(得分:1)

进行初始化时:

Movie movie = new Movie();

空构造函数

public Movie() : this("Jaws", GenreType.Action, 4) { } 

调用具有多个参数的重载构造函数:

public Movie(String title, GenreType type, int rating) { ... }

当你删除这一行:this("Jaws", GenreType.Action, 4) { }时,现在发生的事情是你只调用空的构造函数,它什么都不做。

所以当你打电话

int ratingValue = movie.Rating;

返回整数的默认值zero,因为您确实在其上设置了任何内容。

<强>更新

一个简单的if也许,如果我理解你的意思

假设Rating应大于零。

public override string ToString()
{     
    if (Rating == 0)
    {
        return String.Format("{0}", Title);
    }
    else
    {
        return String.Format(" {0} Genre : {1},  Rating: {2:d} Stars. ", Title, GenType, Rating);
    }
}

答案 1 :(得分:0)

这是因为enumint始终使用默认值0进行初始化。

它不像string - 如果你没有初始化它将等于null。如果您要模仿int的此行为,则可以尝试使用int?类型。

要了解有关此主题的更多详情,请查看Default Values Table (C#)

相关问题