我想知道是否有一种方法可以将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应用到其左侧的对象,请参阅我的更新。 –