Passing a function and parameter list to another function

  • Thread starter Thread starter Jeremy Chapman
  • Start date Start date
J

Jeremy Chapman

I'll try to explain what I would like to do and hopefully someone can tell
me if it's possible.

I have a class called TestClass.
I want to be able to set a parameter in testclass to specify a function
pointer (delegate), but I want to be able to specify any function, not just
a function with a specific signature.

Then I want to be able to call a method of TestClass called load, and pass
it variables that it should call the delagate with.

For example:
class TestClass
{
public function_type_to_call;

public object Load(parameters for the function_type_to_call)
{
if (...)
{
return function_type_to_call(parameter list);
}
else
{
return false;
}
}
}

then I could use TestClass by doing this:

void Method1(int i)
{

}
void Method2(int i, string str)
{

}

TestClass pTest = new TestClass();
pTest.function_type_to_call = Method1;
pTest.Load(10);
pTest.function_type_to_call = Method2;
pTest.Load(10,"test");

I was also hoping to write the class so that in the IDE, when filling in the
parameters for .Load, the user would see the correct tooltips for the
parameters of the method specified in function_type_to_call

Any suggestions?
 
I was also hoping to write the class so that in the IDE, when filling in the
parameters for .Load, the user would see the correct tooltips for the
parameters of the method specified in function_type_to_call

Any suggestions?

Well, the latter is impossible because it's determined at runtime, not
at compile-time. The rest is nearly doable though, using
Delegate.DynamicInvoke and params modifiers. You'd specify the Delegate
to call though, which would be in terms of a target, a type, and the
name of the method.
 
Doesn't that mean that I have to define a delegate for any method I'd want
to call? Theres no way of just specifying any method regardless of whether
theres a delegat or not?
 
Jeremy Chapman said:
Doesn't that mean that I have to define a delegate for any method I'd want
to call? Theres no way of just specifying any method regardless of whether
theres a delegat or not?

Yes, by the name of the method, as I said.
 
Back
Top