c#中不能访问嵌套类中的非静态成员
本文关键字:静态成员 嵌套 不能 访问 | 更新日期: 2023-09-27 18:14:41
namespace DateTimeExpress
{
public class Today
{
private DateTime _CurrentDateTime;
public class Month
{
public int LastDayOfCurrentMonth
{
get
{
return DateTime.DaysInMonth( _CurrentDateTime.Year, _CurrentDateTime.Month);
}
}
}
public Today()
{
}
}
}
如何访问_CurrentDateTime
你可以在c#编程指南的嵌套类型段落中看到一个解释你的问题的例子,他们说:
嵌套类型或内部类型可以访问包含类型或外部类型。来访问包含类型,将其作为构造函数传递给嵌套的类型。
本质上,您需要在嵌套类(Month类)的构造函数中传递对容器(Today类)的引用
public class Today
{
private DateTime _CurrentDateTime;
private Month _month;
public int LastDayOfCurrentMonth { get { return _month.LastDayOfCurrentMonth; }}
// You can make this class private to avoid any direct interaction
// from the external clients and mediate any functionality of this
// class through properties of the Today class.
// Or you can declare a public property of type Month in the Today class
private class Month
{
private Today _parent;
public Month(Today parent)
{
_parent = parent;
}
public int LastDayOfCurrentMonth
{
get
{
return DateTime.DaysInMonth(_parent._CurrentDateTime.Year, _parent._CurrentDateTime.Month);
}
}
}
public Today()
{
_month = new Month(this);
_CurrentDateTime = DateTime.Today;
}
public override string ToString()
{
return _CurrentDateTime.ToShortDateString();
}
}
然后像这样调用
Today y = new Today();
Console.WriteLine(y.ToString());
Console.WriteLine(y.LastDayOfCurrentMonth);