我想将以下 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();
}
}
}
最佳答案
这是你应该做的:
- 将
struct
替换为class
- 与 C++ 不同,C# 对struct
和类进行了更深入的区分.在这种情况下,class
更合适 - 给你的
class
一个构造函数 - 这将帮助你保护year
和title
属性在之后不被更改施工 - 制作一个类数组 - 这样做而不是创建
FILM1
、FILM2
和FILM3
。 - 可选地,为您的类(class)提供一个
ToString()
方法 - 这可以让您更轻松地打印类(class)的实例。
类看起来像这样:
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)
};
关于c# - struct 与 for 循环的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47621919/