我有3个班级,如下所述:
一个拥有要删除的信息,其余两个拥有实际数据。未来将有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
        }
    }
}

08-06 17:06