I am attempting to use a delegate in a way which I have never seen described in my various books.
My questions are:
Is it possible to use delegates in this way? and
If so, how should I alter the code to make use of the delegate?
Specifically I want one function to call another function from a choice of two possible functions.
class Profile
{
private List<verticalCurve> allVCs;
// create allVCs in the constructor
private double nonTrivialFunctionToFindTheRightVCin_allVCs
(double lengthAlong, getSwitchForProfile aDel)
{ // about thirty lines of code which I want to reuse }
public double getElevation(double distanceAlongPfl)
{
// compiler error on the following line:
getSwitchForProfile myDelEL =
new verticalCurve.getSwitchForProfile(verticalCurve.getElevation);
return nonTrivialFunctionToFindTheRightVCin_allVCs
(distanceAlongPfl, myDelEL);
}
public double getSlope(double distanceAlongPfl)
{
// compiler error on the following line:
getSwitchForProfile myDelSL =
new verticalCurve.getSwitchForProfile(verticalCurve.getSlope);
return nonTrivialFunctionToFindTheRightVCin_allVCs
(distanceAlongPfl, myDelSL);
}
} // end class Profile
class verticalCurve
{
private double elevation;
private double slope;
static internal delegate double getSwitchForProfiles(double distanceAlongPfl);
public double getElevation(double distanceAlong)
{ computeElevation then return elevation; }
public slope getSlope(double distanceAlong)
{ compute slope then return slope;}
} // end class verticalCurve
The compiler error states
An object reference is required for the non-static field, method, or property ‘Profile.verticalCurve.getElevation(distanceAlong)’
It appears that my problem is that at the moment I assign a method to the delegate, I do not yet know which instance of verticalCurve it will be called on. But I can’t make verticalCurve.getElevation static because it has to know which verticalCurve it is on.
Sorry for the long setup to the questions. I did try to simplify it, but it seems irreducible beyond this point.
Thanks in advance for your help.
- Paul Schrum
It sounds like you want to create a delegate which takes the object to call it on as a parameter: