我试图找出是否有一种方法可以将func(或类似方法)应用于左侧对象。前任。:
member1.MyFunction()
这是用法的简化上下文。我们得到了ClassA,其中包含ClassB的列表和一种汇总classB元素的方法。并且classB具有两个double类型的属性memberX和memberY。该函数将用于选择我们要汇总的ClassB成员。
我写的行中有一个错误
theSum += TheList[i].TheFunction();
错误是:
CS1061 C#不包含的定义,找不到可以接受类型为第一个参数的扩展方法(是否缺少using指令或程序集引用?)
有谁知道解决方法?我的研究无法使我找到适用于泛型函数左侧的任何内容。
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; }
}
您可以尝试这样的事情:
private double calculateSum(Func<ClassB, double> aFunction)
{
double theSum = 0;
for (int i = 0; i < aList.Count(); i++)
{
theSum += aFunction(aList[i]);
}
return theSum;
}
更新
如果您真的想将func应用于对象的左侧,则可以定义一个扩展方法。
public static class ClassBExtensions
{
public static double Sum(this ClassB arg, Func<ClassB, double> func)
{
return func(arg);
}
}
然后这样称呼它
Func<ClassB, double> func = null; // define your func here
for (int i = 0; i < aList.Count(); i++)
{
theSum += aList[i].Sum(func);
}
return theSum;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句