无法从C#中的嵌套类访问非静态成员

时间:2016-10-23 11:22:40

标签: c# oop

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

1 个答案:

答案 0 :(得分:2)

您可以在Nested Types段的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);