C#-通用类列表

问题描述 投票:3回答:1

我有以下课程:

public abstract class Section
{

}

public class Section<T> : Section where T : new()
{
    public string Type { get; set; }

    public bool IsFocused { get; set; }

    private T sectionData;

    public T SectionData 
    { 
        get => sectionData == null ? sectionData = new T() : sectionData; 
        set => sectionData = value; 
    }
}

public class SectionHeaderData
{
    public string Text { get; set; }

    public int Level { get; set; }
}

public class SectionParagraphData
{
    public string Text { get; set; }
}

然后我创建节并将其存储在List<>中,如下所示:

Section<SectionHeaderData> sectionHeader = new Section<SectionHeaderData>();
sectionHeader.SectionData.Text = "This is Header.";
sectionHeader.SectionData.Level = 3;

Section<SectionParagraphData> sectionParagraph1 = new Section<SectionParagraphData>();
sectionParagraph1.IsFocused = true;
sectionParagraph1.SectionData.Text = "This is Paragraph 1.";

Section<SectionParagraphData> sectionParagraph2 = new Section<SectionParagraphData>();
sectionParagraph2.SectionData.Text = "This is Paragraph 2.";

List<Section> sections = new List<Section>();
sections.Add(sectionHeader);
sections.Add(sectionParagraph1);
sections.Add(sectionParagraph2);

我无法通过IsFocused == true进行LINQ和获取元素:

var focusedSection = sections.FirstOrDefault(x => x.IsFocused == true);

是否可以像正常的SectionHeaderData列表中一样访问SectionParagraphDataList<SomeClass>成员?

编辑1:

根据建议,这是有关我需要的更多信息。

在程序的某个位置将调用一个函数,在该函数中,我需要获取重点部分并能够访问SectionHeaderDataSectionParagraphData的更具体的数据。

例如,我需要读取/设置Text属性的值。

c#
1个回答
4
投票

您需要将属性放入抽象类中:

© www.soinside.com 2019 - 2024. All rights reserved.