簡體   English   中英

無法弄清楚這個C#參考

[英]Cant Figure out this c# reference

我在默認構造函數中使用了“ this”關鍵字,下面是電影類中的代碼

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星。

為什么有人會發生這種情況?

當您進行以下初始化時:

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 ,因為您確實對其進行了設置。

UPDATE

一個簡單的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);
    }
}

這是因為enumint始終使用默認值0進行初始化。

它不像string -如果不初始化,它將等於null 如果要為int模仿此行為,則可以始終嘗試使用int? 類型。

要獲取有關此主題的更多詳細信息,請查看默認值表(C#)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM