, , . :
private Expression<Func<double, double>> myFunc;
private Func<double, double> cachedDelegate;
public void SetFunc(Expression<Func<double,double>> newFunc)
{
this.myFunc = newFunc;
this.cachedDelegate = null;
}
public double ExecFunc(double x)
{
if (this.myFunc != null)
{
if (this.cachedDelegate != null)
{
return this.cachedDelegate(x);
}
else
{
this.cachedDelegate = this.myFunc.Compile();
return this.cachedDelegate(x);
}
}
return 0.0;
}
public string GetFuncText()
{
if (this.myFunc != null)
{
return this.myFunc.ToString();
}
return "";
}
-, . , .
In addition, this approach means that users should use lambda, as method groups are not converted to Expression<Func<>>. However, this does not cause much concern, because instead of transferring the MyMethoduser could go through x => MyMethod(x).
The call code looks something like this:
myObject.SetFunc(x => 2*x);
Console.WriteLine(myObject.GetFuncText());
In conclusion, we note that the above example is not thread safe, so if you expect methods to be called from multiple threads, some kind of synchronization would be appropriate.
source
share