繁体   English   中英

C# - 泛型类列表

[英]C# - List of generic classes

我有以下课程:

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

我无法 LINQ 并通过IsFocused == true获取元素:

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

是否可以像在普通List<SomeClass>列表中一样访问SectionHeaderDataSectionParagraphData成员?

编辑1:

按照建议,这里有更多关于我需要的信息。

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

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

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

public abstract class Section
{
    public string Type { get; set; }

    public bool IsFocused { get; set; }
}

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

我实际上想知道为什么您不将Text属性拉入基类并通过继承解决它(我将从 Jon Skeets 评论中窃取名称):

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

public class SectionHeaderData : SectionData
{
    public int Level { get; set; }
}

public class SectionParagraphData: SectionData { }

然后您可以像这样访问这些字段:

var textSection = sections.OfType<SectionData>().ToList();
textSection[0].Text = "this compiles";

暂无
暂无

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

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