我在另一个类Director()
的构造函数中传递/连接一个类Movie()
时遇到问题。基本上我想要做的是为Movie
和Director
设置两个不同的域,但在Director
类的构造函数中使用Movie
的实例。我在电影类中声明了public Director director;
,但我如何在Movie中将它作为构造函数参数传递?
void Main()
{
Director d1 = new Director("Wachowski Brothers", "USA");
Movie m1 = new Movie("Matrix", d1.Name);
Console.WriteLine(m1.Title);
}
class Movie
{
public Director director;
public string Title { get; set; }
public Movie( string title, Director directorName ){
Title = title;
}
}
class Director
{
public string Name { get; set; }
public string Nationality { get; set; }
public Director(string name, string nationality){
Name = name;
Nationality = nationality;
}
}
答案 0 :(得分:4)
您不想传递Name
,而是整个实例。而不是
Movie m1 = new Movie("Matrix", d1.Name);
你的意思是
Movie m1 = new Movie("Matrix", d1);
答案 1 :(得分:2)
Movie m1 = new Movie("Matrix", d1.Name);
应该是
Movie m1 = new Movie("Matrix", d1);
答案 2 :(得分:1)
试试这个:
void Main()
{
Director d1 = new Director("Wachowski Brothers", "USA");
Movie m1 = new Movie("Matrix", d1);
Console.WriteLine(m1.Title);
Console.WriteLine(m1.director.Name);
}
class Movie
{
public Director director;
public string Title { get; set; }
public Movie( string title, Director directorName ){
Title = title;
director=directorName;
}
}
class Director
{
public string Name { get; set; }
public string Nationality { get; set; }
public Director(string name, string nationality){
Name = name;
Nationality = nationality;
}
}
答案 3 :(得分:0)
你可以在同一时间电影中创建导演:
void Main()
{
Movie m1 = new Movie("Matrix", "Wachowski Brothers", "USA");
Console.WriteLine(m1.Title);
Console.WriteLine(m1.director.Name);
}
class Movie
{
public Director director;
public string Title { get; set; }
public Movie( string title, Director director ){
Title = title;
this.director=director;
}
public Movie( string title, string DirectorName, string DirectorNationality){
Title = title;
director=new Director(DirectorName, DirectorNationality);
}
}
class Director
{
public string Name { get; set; }
public string Nationality { get; set; }
public Director(string name, string nationality){
Name = name;
Nationality = nationality;
}
}
答案 4 :(得分:0)
喜欢上面的帖子提示。你的功能签名。
public Movie( string title, Director directorName )
调用Director类型的对象。你只传递名字, 这是一个字符串。命名在这里很重要。您正在调用Director“directorName”。这就是你感到困惑的地方。