我有 3 个类,如下所述: 一类具有要删除的信息,其余两类具有实际数据。 future 数据会超过30类
public class RemovalInformation<T> where T:class
{
public string TagName { get; set; }
public T Data { get; set; }
public Func<T, bool> RemovalCondition { get; set; }
}
public class PropertyReportData
{
public string PropertyName { get; set; }
}
public class ValuationData
{
public DateTime ValuationDate { get; set; }
}
我有一个我想要处理的下面的 ArrayList
var removals = new ArrayList
{
new RemovalInformation<PropertyReportData>
{
Data = commercialReportData?.PropertyDetail,
TagName = nameof(PropertyReportData.PropertyName),
RemovalCondition = property => string.IsNullOrWhiteSpace(property.PropertyName),
},
new RemovalInformation<ValuationData>
{
Data = commercialReportData?.ValuationData,
TagName = nameof(ValuationData.ValuationDate),
RemovalCondition = property => property.ValuationDate< DateTime.Today,
}
};
ProcessRemovals(removals);
方法ProcessRemovals是
private void ProcessRemovals(ArrayList removals)
{
foreach (RemovalInformation<PropertyReportData> item in removals)
{
var deleteItem = item.RemovalCondition.Invoke(item.Data);
if (deleteItem)
{
//do something here
}
}
}
这里的问题是,在 foreach 循环中我只能访问一种类型的 RemovalInformation。有什么方法可以遍历多种类型的 RemovalInformation 的列表
最佳答案
你可以使用这样的界面:
public interface IProcessRemoval
{
bool Execute();
}
只是实现它:
public class RemovalInformation<T> : IProcessRemoval where T:class
{
public string TagName { get; set; }
public T Data { get; set; }
public Func<T, bool> RemovalCondition { get; set; }
public bool Execute()
{
if (RemovalCondition != null)
{
return RemovalCondition(Data);
}
return false;
}
}
然后迭代:
private void ProcessRemovals(ArrayList removals)
{
foreach (IProcessRemoval item in removals)
{
var deleteItem = item.Execute();
if (deleteItem)
{
//do something here
}
}
}
关于c# - 遍历具有多种类型的通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404994/