Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何访问泛型内的属性?_C#_Class_Generics - Fatal编程技术网

C# 如何访问泛型内的属性?

C# 如何访问泛型内的属性?,c#,class,generics,C#,Class,Generics,我有一个基类,它的属性总是.Balance。我需要遍历一个类列表,并将余额添加到一起。这一切都很好,但也可以传递两个派生类,资产和负债。如何在不重载GetTotalBalance的情况下使其正常工作?此外,如何要求从类AccountBase派生,从而保证包含.Balance属性?可能吗 private float GetTotalBalance<T>(List<T> accountList) where T : class { float totalAssets

我有一个基类,它的属性总是
.Balance
。我需要遍历一个类列表,并将余额添加到一起。这一切都很好,但也可以传递两个派生类,
资产
负债
。如何在不重载GetTotalBalance的情况下使其正常工作?此外,如何要求
从类
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;
}
private float GetTotalBalance(List accountList),其中T:class
{
浮动总资产=0.0f;
对于(int-assetIndex=0;assetIndex
您正在寻找通用合同:

where T : YourBaseClass
或者,使函数非泛型,并接受一个
IEnumerable
(因为接口是协变的)

在进行此操作时,将函数更改为

return accounts.Sum(a => a.Balance);

其中T:AccountBase
?响应太慢,他说的是:-)