我有一个总是具有.Balance
属性的基类。我需要遍历一个类列表并将余额添加到一起。这一切都很好,但是有两个派生类,Assets
和Liabilities
也可以传递。如何在不重载GetTotalBalance
的情况下一般地完成这项工作?除此之外,我如何才能要求<T>
从类AccountBase
派生,这样才能保证包含.Balance
属性?这可能吗?
private float GetTotalBalance<T>(List<T> accountList) where T : class
{
float totalAssets = 0.0f;
for (int assetIndex = 0; assetIndex < accountList.Count; assetIndex++)
{
totalAssets += accountList[assetIndex].Balance;
}
return totalAssets;
}
答案 0 :(得分:1)
您正在寻找通用约束:
where T : YourBaseClass
或者,使函数非泛型,并接受IEnumerable<YourBaseClass>
(因为接口是协变的)。
当你在它时,将功能改为
return accounts.Sum(a => a.Balance);