我想知道是否有一種方法可以將func(或類似方法)應用於左側對象。 例如:C#func <>應用於左側對象
member1.MyFunction()
下面是簡化的使用情況。我們得到了ClassA,它包含一個ClassB的List和一個總結classB的元素的方法。 classB具有兩個屬性memberX和memberY,屬於double類型。 func是用來選擇我們想要總結的ClassB的最終成員。
我有在我寫
theSum += TheList[i].TheFunction();
該錯誤是行一個錯誤:
CS1061 C#不包含的定義,並沒有擴展方法接受的第一個參數類型可以找到(您是否缺少使用指令或程序集引用?)
有沒有人知道解決方法?我的研究不能讓我知道任何適用於通用函數左側的東西。
public class ClassA
{
public List<ClassB> TheList;
public ClassA()
{
ClassB m1 = new ClassB(1, 2);
ClassB m2 = new ClassB(1, 2);
ClassB m3 = new ClassB(1, 2);
TheList= new List<ClassB>() { m1, m2, m3 };
}
private double CalculateSum(Func<double> TheFunction)
{
double theSum = 0;
for (int i = 0; i < TheList.Count(); i++)
{
theSum += TheList[i].TheFunction();
// I'd like to use the previous line instead of having to write
// a function for both of the following.
// theSum += TheList[i].GetMember1();
// theSum += TheList[i].GetMember2();
}
return theSum;
}
}
public class ClassB
{
private double memberX;
private double memberY;
public ClassB(double x, double y)
{
memberX = x;
memberY = y;
}
public double GetMember1() { return memberX; }
public double GetMember2() { return memberY; }
}
我試圖避免這種情況,但看到答案(和搜索結果)我相信沒有其他方式使用Func <>或任何其他類似的方法。 –
如果您想將func應用到其左側的對象,請參閱我的更新。 –