我正在使用ASP.NET MVC。我有父母:
public class ReportFilterBuilderStruct
{
public string PropName { get; set; }
public string ClassName { get; set; }
public string SubListName { get; set; }
//public virtual string SecondaryPropName { get; set; }
public ReportFilterBuilderStruct(string inpPropName, string inpClassName, string inpSubListName)
{
PropName = inpPropName;
ClassName = inpClassName;
SubListName = inpSubListName;
}
}
还有一个孩子:
public class DateReportFilterBuilderStruct : ReportFilterBuilderStruct
{
public string SecondaryPropName { get; set; }
public DateReportFilterBuilderStruct(string inpPropName, string inpSecondaryPropName, string inpClassName, string inpSubListName) : base(inpPropName, inpClassName, inpSubListName)
{
SecondaryPropName = inpSecondaryPropName;
}
}
}
我将在视图中使用它来存储有关我的模型类属性的一些数据。
editorListProp
将同时存储ReportFilterBuilderStruct
和DateReportFilterBuilderStruct
,这就是为什么它是父类对象的List
。
var editorListProp = new List<NTStock.Models.ReportFilterBuilderStruct>();
现在我想访问它们:
if (subItem.GetType() == typeof(NTStock.Models.ReportFilterBuilderStruct))
{
<div class="row align-items-center">
@Html.DisplayName(subItem.PropName)
</div>
<div class="row align-items-center mb-2">
@Html.Editor(subItem.PropName, "", new { htmlAttributes = new { @class = subItem.ClassName } })
</div>
}
else
{
<div class="row align-items-center">
@Html.DisplayName(subItem.PropName)
</div>
<div class="row align-items-center mb-2">
<div class="col-6">
From:
@Html.Editor(subItem.PropName, "", new { htmlAttributes = new { @class = subItem.ClassName } })
</div>
<div class="col-6">
Till:
@Html.Editor(subItem.SecondaryPropName, "", new { htmlAttributes = new { @class = subItem.ClassName } })
</div>
</div>
}
重点是,我无法访问SecondaryPropName
,即使我确保当前的subItem
确定类型为DateReportFilterBuilderStruct
。
答案 0 :(得分:2)
您必须将Long
投射到subItem
,例如:
DateReportFilterBuilderStruct
答案 1 :(得分:1)
这种方法适用于像Python这样的动态类型语言,但不适用于C#。您的列表属于List<ReportFilterBuilderStruct>
类型。当您从列表中访问项目时,例如list[0]
,即使您在ReportFilterBuilderStruct
存储DateReportFilterBuilderStruct
并且GetType()
正确返回DateReportFilterBuilderStruct
,也会返回else
类型的对象。
在DateReportFilterBuilderStruct
分支中,您首先必须将项目转换为else
{
@{ var dateReport = (DateReportFilterBuilderStruct)subItem; }
<div class="row align-items-center">
@Html.DisplayName(dateReport.PropName)
</div>
<div class="row align-items-center mb-2">
<div class="col-6">
From:
@Html.Editor(dateReport.PropName, "", new { htmlAttributes = new { @class = dateReport.ClassName } })
</div>
<div class="col-6">
Till:
@Html.Editor(dateReport.SecondaryPropName, "", new { htmlAttributes = new { @class = dateReport.ClassName } })
</div>
</div>
}
:
document.querySelectorAll('math :not([style*="display:none"])');