I am having issue on passing/ connecting one class Director()
in the constructor of another class Movie()
. Basically what I want to do is to have two different domain for Movie
and Director
but use instance of Director
in constructor of the Movie
class. I have a declaration of public Director director;
in the movie class but how I can pass it as constructor parameter in 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;
}
}
You don't want to pass the Name
, but the whole instance. So instead of
Movie m1 = new Movie("Matrix", d1.Name);
you mean
Movie m1 = new Movie("Matrix", d1);
Movie m1 = new Movie("Matrix", d1.Name);
应该
Movie m1 = new Movie("Matrix", d1);
try this :
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;
}
}
You can create director in same time movie like this:
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;
}
}
Like the above posts suggest. Your function signature.
public Movie( string title, Director directorName )
calls for an object of type Director. You are passing in only the name, which is a String. Naming is important here. You are calling Director "directorName". That's where you're getting confused.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.