c# - 遍历具有多种类型的通用列表

标签 c# arraylist expression generic-list

我有 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/

相关文章:

c# - 如何在 C# .NET 中为子类设置特定属性?

c# - 从 Tap 事件获取绑定(bind)对象

c - 什么是 int a=(i*+3); c编译器将如何执行它?

C 中的复合语句表达式

c# - 模拟存储库和测试参数化服务方法

c# - 如何确定 POP3 邮件附件的文件大小

c# - Entity Framework 的日期时间格式

java - 在 Java 中将文本文件放入二维不规则数组中

java - 对 Arraylist 对象进行排序

java - 如何复制迭代器对象?