c# - struct 与 for 循环的使用

标签 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();
        }
    }
}

最佳答案

这是你应该做的:

  • struct 替换为 class - 与 C++ 不同,C# 对 struct 和类进行了更深入的区分.在这种情况下,class 更合适
  • 给你的 class 一个构造函数 - 这将帮助你保护 yeartitle 属性在之后不被更改施工
  • 制作一个类数组 - 这样做而不是创建 FILM1FILM2FILM3
  • 可选地,为您的类(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/

相关文章:

c# - 在屏幕调整大小时自动移动剑道通知

c# - 在 C# 中从 SQL Server 检索大量数据的最简单方法

c# - Datagrid 按需卸载

java - 非循环依赖原则 - 组件依赖循环如何成为 "morning-after syndrome"的原因?

c++ - 重载以结构继承作为参数的函数 C++

c# - 这个说法有什么问题?

go - 在方法或构造函数级别进行 Nil 处理?

c - typedef 结构错误。 '*' token 之前

尽管函数和结构是包含的头文件的成员,但 C 错误 : implicit declaration of function and storage size isn't known,

struct - 在 Rust 中将结构解包为左值元组