繁体   English   中英

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

[英]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()
        {

        }
    }
}

如何访问_CurrentDateTime

您可以在《 C#编程指南》的“ 嵌套类型”段落中看到一个说明您问题的示例,其中说:

嵌套或内部类型可以访问包含或外部类型。 要访问包含的类型,请将其作为构造函数传递给嵌套类型。

本质上,您需要在嵌套类(月类)的构造函数中传递对容器(今日类)的引用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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