gpt4 book ai didi

C# - 泛型类列表

转载 作者:行者123 更新时间:2023-12-02 14:30:42 24 4
gpt4 key购买 nike

我有以下类(class):

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

可以访问SectionHeaderData & SectionParagraphData成员(member)就像平常一样 List<SomeClass>列表?

编辑 1:

根据建议,这里有一些关于我需要的更多信息。

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

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

最佳答案

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

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

public bool IsFocused { get; set; }
}

For example, I will need to read / set the value of the Text property.

我实际上想知道为什么你不将 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";

关于C# - 泛型类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60341141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com