将Enum作为字符串传递给构造函数的问题

时间:2017-09-22 16:44:14

标签: c#

我正在尝试将枚举传递给Movie()

的构造函数
  

电影m1 =新电影(" Matrix",MovieGenre.Action,8,2000);

但收到此错误:

  

无法转换自' UserQuery.MovieGenre'到'字符串'

你能告诉我我做错了什么以及如何解决这个问题吗?

void Main()
{
    enum MovieGenre{
        Action,
        Horor,
        Drama,
        Comedy,
        Thriller
    }
    Movie m1 = new Movie("Matrix", MovieGenre.Action, 8, 2000 );
}

class Movie
{

    public string Title { get; set; }
    public string Genre { get; set; }
    public int Rank { get; set; }
    public int Year { get; set; }
    public Movie( string title, string genre, int rank, int year ){
     Title = title;
     Genre = genre;
     Rank = rank;
     Year = year;
    }
}

1 个答案:

答案 0 :(得分:2)

Movie m1 = new Movie("Matrix", MovieGenre.Action.ToString(), 8, 2000 );

:)或

public Movie( string title, MovieGenre genre, int rank, int year ){

编辑: 这是你的片段。 (格式化是搞砸的,无法弄清楚)

using System;

public class Program
{
  public static void Main()
  {
    Movie m1 = new Movie("Matrix", MovieGenre.Action, 8, 2000 );
  }
}

public enum MovieGenre
{
  Action,
  Horror,
  Drama,
  Comedy,
  Thriller
}

public class Movie
{

public string Title { get; set; }
public MovieGenre Genre { get; set; }
public int Rank { get; set; }
public int Year { get; set; }
public Movie( string title, MovieGenre genre, int rank, int year ){
 Title = title;
 Genre = genre;
 Rank = rank;
 Year = year;
}

}