使用struct for for循环

时间:2017-12-03 18:44:48

标签: c# struct

我想将c ++代码翻译成c#。但我不知道如何循环播放" FILM" (比如c ++中的film [n]),而不是每个人单独调用。

有人也可以提出更好地翻译此代码的建议吗?

C ++代码

// array of structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct movies_t {
  string title;
  int year;
} films [3];

void printmovie (movies_t movie);

int main ()
{
  string mystr;
  int n;

  for (n=0; n<3; n++)
  {
    cout << "Enter title: ";
    getline (cin,films[n].title);
    cout << "Enter year: ";
    getline (cin,mystr);
    stringstream(mystr) >> films[n].year;
  }

  cout << "\nYou have entered these movies:\n";
  for (n=0; n<3; n++)
    printmovie (films[n]);
  return 0;
}

void printmovie (movies_t movie)
{
  cout << movie.title;
  cout << " (" << movie.year << ")\n";
}

我的c#尝试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MAKEGROUP {
    class Program {
        struct movies_t {
            public string title;
            public int year;

            public  void printmovie(movies_t movie) {
                Console.Write(movie.title);
                Console.Write(" (");
                Console.Write(movie.year);
                Console.Write(")\n");
            }
        }

        static void Main(string[] args) {

            movies_t FILM = new movies_t();
            movies_t FILM1 = new movies_t();
            FILM1.title = "Hero";
            FILM1.year = 1990;

            movies_t FILM2 = new movies_t();
            FILM2.title = "Titanic";
            FILM2.year = 1997;

            movies_t FILM3 = new movies_t();
            FILM3.title = "Mission impossible";
            FILM3.year = 1996;

            // How can I use for loop 
            // for the following code

            FILM.printmovie(FILM1);
            FILM.printmovie(FILM2);
            FILM.printmovie(FILM3);

            Console.ReadKey();
        }
    }
}

4 个答案:

答案 0 :(得分:4)

这是你应该做的:

  • struct替换为class - 与C ++不同,C#对struct和类进行了更深入的区分。在这种情况下,class更合适
  • 授予class构造函数 - 这可以帮助您保护yeartitle属性在构建后不被更改
  • 制作班级数组 - 执行此操作,而不是创建FILM1FILM2FILM3
  • (可选)为您的班级提供ToString() methid - 这样可以让您更轻松地打印课程实例。

这个课程看起来像这样:

class Film {
    string Title {get;}
    int Year {get;}
    public Film(string title, int year) {
        Title = title;
        Year = year;
    }
}

数组初始化将如下所示:

Film[] film = new Film[] {
    new Film("Hero", 1990)
,   new Film("Titanic", 1997)
,   new Film("L'Arroseur Arrosé", 1895)
};

答案 1 :(得分:2)

以下是如何最低限度地重写:

var films = new List<movies_t>();

var hero = new movies_t { 
    title = "Hero",
    year = 1990
};

films.Add(hero);

//  Similar syntax for the same thing:
fiilms.Add(new movies_t { title = "Titanic", year = 1997 });

但你也应该做其他改变。

不要将movies_t作为结构。把它变成一个班级。 struct表示这两种语言有所不同。请使用C#命名约定。

在C#中,您的代码看起来应该更像这样:

public class Movie
{
    public Movie() 
    {
    }

    public Movie(string title, int year) 
    {
        this.Title = title;
        this.Year = year;
    }

    public string Title;
    public int Year;

    public override String ToString()
    {
        return $"{Title} ({Year})";
    }
}

//  ...snip...

var films = new List<Movie>();

var hero = new Movie("Hero", 1990);

films.Add(hero);

//  Similar syntax for the same thing:
films.Add(new Movie("Titanic", 1997));

foreach (var film in films)
{
    //  This will call Movie.ToString() to "convert" film to a string. 
    Console.WriteLine(film);
}

答案 2 :(得分:1)

这里是使用linqpad测试的工作代码(解释如下):

void Main()
{
    var films = new List<Movie> {
        new Movie("Hero",1990 ),
        new Movie("Titanic",1997 ),
        new Movie("Mission impossible",1996 ),
    };

    foreach(var film in films)
    {
        Console.WriteLine(film.GetCompleteTitle());
    }
}


class Movie
{
    public String Title { get; }
    public Int32 Year { get; }

    public Movie(String title, Int32 year) => (Title, Year) = (title, year);

    public String GetCompleteTitle() => $"{Title} ({Year})";
}

说明:

  1. 数组不是必需的如果大小可以更改并且您希望使初始化更具可读性
  2. 你应该使用,你不需要值类型来处理电影概念
  3. 使用构造函数仅提供一种初始化变量的方法
  4. 请尝试通过将打印件移到方法
  5. ,避免将您的课程与控制台耦合
  6. 隐藏字段并将其设为只读auto-implemented properties以隐藏字段实施细节
  7. 您可以使用string interpolation以可读的方式撰写字符串
  8. Expression-bodied members可用于返回方法或使用较少的代码进行分配
  9. Tuple deconstruction可用于将构造函数参数分配给属性并使代码更紧凑

答案 3 :(得分:1)

public static void Main()
{
    Movie[] movies = new Movie[]
    {
        new Movie("Hero", 1990),
        new Movie("Titanic", 1997),
        new Movie("Mission Impossible", 1996),
    };

    for (Int32 i = 0; i < movies.Length; ++i)
        Console.WriteLine(movies[i].ToString());
}

另外,使用class代替struct,因为它更合适(有关更多信息,请阅读this)。这是我建议你的(符合上面的工作例子):

public class Movie
{
    public String Title { get; private set; }
    public Int32 Year { get; private set; }

    public Movie(String title, Int32 year)
    {
        Title = title;
        Year = year;
    }

    public override String ToString()
    {
        return (title + " (" + year.ToString() + ")");
    }
}