c#访问父类的子类的嵌套类数据类型

时间:2015-11-11 12:42:13

标签: c# class model-view-controller nested custom-data-type

我有一个相当复杂的自定义数据类型,其中许多属性以有组织的格式存储。以下只是它的一小部分,所以看起来可能看起来没有必要这样做,但我总共接近200个属性,我只是不想给这个问题带来不必要的混淆。

在以下模型的代码中,我需要拥有属性:

Chiller.GeneralInformation.PrimaryVoltage

返回以下内容:

Chiller.Controller.PrimaryVoltage.Voltage + " / " + Chiller.Controller.PrimaryVoltage.Phases;

实现这一目标的最佳方法是什么?

namespace WebQuoter.Models
{
    public class Chiller
    {
        public MyGeneralInformation GeneralInformation { get; set; }
        public MyController Controller { get; set; }

        public class MyGeneralInformation
        {
            public string AssemblyID { get; set; }
            public string PrimaryVoltage
            {
                get
                {
                    return "HELP";
                }
            }
        }

        public class MyController
        {
            public MyPrimaryVoltage PrimaryVoltage { get; set; }

            public class MyPrimaryVoltage
            {
                public string Voltage { get; set; }
                public string Phases { get; set; }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

就我个人而言,我没有理由以这种方式设计它,但如果你想要的话,你需要引用Chiller内的父MyGeneralInformation

public class Chiller
{
    private MyGeneralInformation information;

    public MyGeneralInformation GeneralInformation
    {
        get
        {
            return information;
        }
        set
        {
            information = value;
            information.parent = this;
        }
    }
    public MyController Controller { get; set; }

    public class MyGeneralInformation
    {
        internal Chiller parent;
        public string AssemblyID { get; set; }
        public string PrimaryVoltage
        {
            get
            {
                return string.Format(
                    "{0}/{1}",
                    parent.Controller.PrimaryVoltage.Voltage,
                    parent.Controller.PrimaryVoltage.Phases);
            }
        }
    }

    public class MyController
    {
        public MyPrimaryVoltage PrimaryVoltage { get; set; }

        public class MyPrimaryVoltage
        {
            public string Voltage { get; set; }
            public string Phases { get; set; }
        }
    }
}

但是,当您创建MyGeneralInformation并且parentnull导致PrimaryVoltage引发异常时,这会出现问题。你可以在那里放null张,但我个人不明白你为什么不这样做

public class Chiller
{
    public string AssemblyID { get; set; }

    public string PrimaryVoltage
    {
        get
        {
            return string.Format("{0}/{1}", Voltage, Phases);
        }
    }

    public string Voltage { get; set; }

    public string Phases { get; set; }
}