从另一个类中的其他类创建属性时出错

时间:2017-04-20 16:44:22

标签: c#

你能否告诉我为什么会收到这个错误

  

CS0029无法将类型'string'隐式转换为'UserQuery.Director'

on

  

m.DirectorName =“某人”;

在:

void Main()
{
    Movie m = new Movie();
    m.Name = "Matrix";
    m.DirectorName = "Someone";
    Console.WriteLine(m.Name);
}

public class Director
{
    public string Name { get; set;}
}

public class Movie
{
    public string Name { get; set;}
    public Director DirectorName { get; set; }
}

3 个答案:

答案 0 :(得分:3)

DirectorName不是字符串。所以你不能给它分配一个字符串。您可以为其分配Director。由于DirectorName属性实际上代表一个Director,因此命名不佳。将您的电影课改为:

public class Movie
{
     public string Name { get; set; }

     public Director MovieDirector { get; set; }
}

你的方法代码:

 //Create a movie and set the name property
 Movie m = new Movie();
 m.Name = "Matrix";

 //Create a director and set the name property
 Director d = new Director();
 d.Name = "Someone";

 //Assign the director to the movie by setting the MovieDirector property
 m.MovieDirector = d;

 //Print out the movie's director's name.
 Console.WriteLine(m.MovieDirector.Name);

使用对象初始化器还有一个简写语法:

Movie m = new Movie
{
    Name = "Matrix",
    MovieDirector = new Director { Name = "Someone" }
};

答案 1 :(得分:0)

DirectorName是一种Director,您正在尝试将字符串值传递给它。

答案 2 :(得分:-1)

在你的课堂电影中,你有一个班级的参考。如果要更改director类中的字符串,请执行m.DirectorName.Name