【发布时间】:2014-10-09 12:31:21
【问题描述】:
有什么方法可以创建仅包含其他类的 Main 类的对象。
public class City
{
public int CityId { get; set; }
public string CItyName { get; set; }
}
public class State
{
public int StateId { get; set; }
public string StateName { get; set; }
}`
public class CurrentPresident
{
public int PresidentId { get; set; }
public string PresidentName { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public CurrentPresident President { get; set; }
public IList<State> States { get; set; }
public IList<City> Cities { get; set; }
}
我有四个不同的班级,我的 Country 班级拥有不同的班级作为成员 现在我想创建仅 Country 类的对象,而不是 Country 类内部的其他类。
Country country=new Country();
为了更清楚,我不想创建 City、State 和 CurrentPresident 类的对象。我只想创建 Country Class 的对象,该对象反过来也实例化 Country 类中的其他类。
非常感谢
【问题讨论】:
-
您已经发布了解决方案:
Country country=new Country();。如果您还想初始化其他类型,则应提供适当的构造函数或内联初始化。 -
@Tim 感谢您的快速回复,但我的声明只创建 Country 类的对象,而不是 Country 类中的其他类。
-
如果我把这行 Country count = new Country(); count.President.PresidentId = 1;因为没有实例化总统,我会得到错误。
-
你总是可以在你的类中提供构造函数,以你想要的方式初始化字段。所以你可以提供一个空的构造函数(
public Country(){States=new List<State>();CurrentPresident=new President();...}),你可以根据需要在其中初始化对象。 -
访问尚未定义的总统毫无意义。因此,恕我直言,为每个国家/地区提供默认总统甚至是一个错误。如果你想知道一个国家的总统,你必须先指定它。例如:
c.President = new CurrentPresident{ PresidentId = 1, PresidentName = "Obama" };