简体   繁体   中英

Can not access a non-static member from nested class in C#

namespace DateTimeExpress
{
    public class Today
    {
        private DateTime _CurrentDateTime;


        public class Month 
        {
            public int LastDayOfCurrentMonth
            {
                get
                {
                    return DateTime.DaysInMonth( _CurrentDateTime.Year, _CurrentDateTime.Month);
                }
            }
        }

        public Today()
        {

        }
    }
}

How can I access _CurrentDateTime

You can see an example that explains your problem in the C# Programming Guide at Nested Types paragraph where they say:

The nested, or inner type can access the containing, or outer type. To access the containing type, pass it as a constructor to the nested type.

Essentially you need to pass a reference to the container (Today class) in the constructor of the nested class (Month class)

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();
    }
}

And call it with something like this

Today y = new Today();
Console.WriteLine(y.ToString());
Console.WriteLine(y.LastDayOfCurrentMonth);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM