這是另一篇文章的延續。我正在嘗試創建一個接口,使我能夠瀏覽一組對象,並訪問該對象的屬性名稱。如何獲取我的ReportItems的類型
A Report
對象將有ReportSections
。 A ReportSection
將有一個ICollection項目將根據使用情況而改變。
下面是我現在想要定義它的方法。
public interface IReport
{
string ReportName { get; set; }
ICollection<IReportSection> ReportSections { get; }
}
public interface IReportSection
{
string ReportSectionName { get; set; }
ICollection ReportItems { get; }
}
public abstract class ReportBase : IReport
{
virtual public string ReportType { get; set; }
virtual public string ReportName { get; set; }
virtual public ICollection<IReportSection> ReportSections { get; set; }
}
public abstract class ReportSectionBase : IReportSection
{
public string ReportSectionName { get; set; }
public ICollection ReportItems { get; set; }
}
在我的代碼,我這樣做:
public class BookAffiliates : ReportSectionBase
{
public override string ReportSectionName { get { return "Book Affiliates"; } }
public override ICollection ReportItems { get; set; }
}
public class SomeClass
{
public ICollection<AuthorsViewModel> Authors { get; set; }
public ICollection<ProjectSubmissionViewModel> Submissions { get; set; }
public string ProcessAuthorsReport()
{
var report = new ContribAuthorsReport{ ReportType = "CSV" };
var authorAffil = new BookAffiliates {ReportItems = Authors };
report.ReportSections.Add(chapAffil);
var submissionAffil = new BookAffiliates {ReportItems = Submissions};
report.ReportSections.Add(submissionAffil);
return RenderReport(report)
}
}
在RenderReport
我想通過收藏走路和使用PropertyNames:
private string RenderReport(ReportBase currentReport)
{
var reportBody = new StringBuilder();
reportBody.Append(currentReport.ReportName + Environment.NewLine + Environment.NewLine);
foreach (var thisSection in currentReport.ReportSections)
{
reportBody.Append(thisSection.ReportSectionName + Environment.NewLine);
/// ---- Here! Here! I don't know what type, I want the
/// code to get the type based on ReportSectionBase<T>
var firstItem = thisSection.ReportItems.OfType<???Type???>().FirstOrDefault();
// I would actually like to go through each property of
// the ReportItem type and list it here.
foreach(var prop in firstItem.GetType().GetProperties())
{
reportBody.AppendLine(string.Format("{0}:{1}" prop.Name, prop.Value));
}
}
return reportBody.ToString();
}
我不知道如何最好地定義這一點。我很確定我以前做過這件事,但這不是我想要的。
[如何獲得某個類的屬性列表?](http://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-類) – stuartd
請不要重複。我添加了更多評論。 –
'T'是什麼類? – stuartd