M.S*_*.S. 3 c# expression arraylist generic-list
我有 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; }
}
Run Code Online (Sandbox Code Playgroud)
我有一个下面的 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);
Run Code Online (Sandbox Code Playgroud)
方法 ProcessRemovals 是
private void ProcessRemovals(ArrayList removals)
{
foreach (RemovalInformation<PropertyReportData> item in removals)
{
var deleteItem = item.RemovalCondition.Invoke(item.Data);
if (deleteItem)
{
//do something here
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,在 foreach 循环中我只能访问一种类型的 RemovalInformation 。有没有办法迭代多种类型的 RemovalInformation 的列表
小智 5
您可以使用一个接口,如下所示:
public interface IProcessRemoval
{
bool Execute();
}
Run Code Online (Sandbox Code Playgroud)
只需实现它即可:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后迭代:
private void ProcessRemovals(ArrayList removals)
{
foreach (IProcessRemoval item in removals)
{
var deleteItem = item.Execute();
if (deleteItem)
{
//do something here
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2455 次 |
| 最近记录: |