我有以下几个类:
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>
列表一样访问 SectionHeaderData
和 SectionParagraphData
成员?
编辑 1:
如建议所述,这里有更多关于我需要的信息。
在程序的某个时刻,将调用一个函数,在该函数中,我需要获取焦点部分,并能够访问 SectionHeaderData
或 SectionParagraphData
的更具体数据。
例如,我需要读取/设置 Text
属性的值。
Type
和IsFocused
移到非泛型的Section
类中,这样就可以正常工作了。只有SectionData
属性涉及到T
,所以它是泛型类型中唯一需要保留的部分。 - Jon Skeet.OfType<Section<SectionHeaderData>>()
来过滤特定类型的对象。然后,您可以引用这些类型的属性。 - D Stanleyabstract object SectionData { get; }
属性。基本上,我们目前正在猜测您需要什么 - 请使用更多细节编辑问题。 - Jon SkeetSectionHeaderData
和SectionParagraphData
均继承自SectionData
类,该类包含一个Text
属性。然后你可以直接将其转换为SectionData
(或在非泛型类中仅需将属性命名为SectionData
并相应地限制T
)。 - Jon Skeet