导致递归强制转换导致StackOverflow异常的隐式运算符

时间:2019-02-16 12:37:21

标签: c#

我已经为Class,Section,Employee模型创建了ViewModel类

Class的VClass和VSection隐式运算符正在Class控制器的Index.cshtml上递归分类。
自从我在VClass和Classs中添加了Sections,在VSection类中添加了Employee之后,就开始了递归转换。

请原谅我以下内容:
VSections中的Classs属性不是列表。它拥有该部分的Class实体。对其进行多重化只是为了减少混乱

班级

public class VClass
    {
        public int ClassId { get; set; }

    [Required(ErrorMessage = "Class Name is required")]
    [Display(Name = "Class Name")]
    public string ClassName { get; set; }

    public int? ClassOrder { get; set; }

    public virtual ICollection<VSection> Sections { get; set; }

    public static implicit operator VClass(Classes classes)
    {
        return new VClass
        {
            ClassId = classes.ClassId,
            ClassName = classes.ClassName,
            ClassOrder = classes.ClassOrder,
            Sections = classes.Sections != null ? new List<VSection>(classes.Sections.Select(a => (VSection)a)) : null
        };
    }

    public static implicit operator Classes(VClass vclasses)
    {
        return new Classes
        {
            ClassId = vclasses.ClassId,
            ClassName = vclasses.ClassName,
            ClassOrder = vclasses.ClassOrder,
            Sections = vclasses.Sections != null? new List<Sections>(vclasses.Sections.Select(a => (Sections)a)) : null
        };
    }

}  

部分

public class VSection
    {
        public int SectionId { get; set; }

    [Required(ErrorMessage = "Section Name is required")]
    [Display(Name = "Section Name")]
    public string SectionName { get; set; }

    [Required(ErrorMessage = "Class is required")]
    [Display(Name = "Class Name")]
    public Nullable<int> ClassId { get; set; }

    [Required(ErrorMessage = "Class Teacher is required")]
    [Display(Name = "Class Teacher")]
    public Nullable<int> ClassTeacher { get; set; }

    public virtual VClass Classes { get; set; }
    public virtual VEmployee Employee { get; set; }

    public static implicit operator VSection(Sections section)
    {
        return new VSection
        {
            ClassId = section.ClassId,
            SectionName = section.SectionName,
            ClassTeacher = section.ClassTeacher,
            SectionId = section.SectionId,
            Classes = section.Classes,
            Employee = section.Employee
        };
    }

    public static implicit operator Sections(VSection vsection)
    {
        return new Sections
        {
            SectionId = vsection.SectionId,
            SectionName = vsection.SectionName,
            ClassId = vsection.ClassId,
            ClassTeacher = vsection.ClassTeacher,
            Classes = vsection.Classes,
            Employee = vsection.Employee
        };
    }
}    

StackOverflowException

0 个答案:

没有答案