How to call delegated methods individually without dynamic binding?

M

mmmpie

I want to be able to hand off the inner functionality of a loop to a
delegate. However, I also need to be able to call one of a number of
delegates based on the context of the loop ( in this case what level Im
in in a tree ). Using delegates seems like an easy way to implement all
of the management, and is well understood.
Where Im having trouble is invoking a _single_ delegate out of the
invocation list.

Some simple test code:

class DelegateHolder
{
public TestDelegate imATest;

public void RunDelegate()
{
// this works
foreach (TestDelegate wc in imATest.GetInvocationList())
{
wc(1);
}

// this doesnt - runtime exception casting to TestDelegate[]
TestDelegate[] ds;
ds = (TestDelegate[])imATest.GetInvocationList();
ds[0](1);
ds[1](1);
ds[2](1);
}
}
 
W

William Stacey [MVP]

Maybe something like:

Delegate[] da = rdel.GetInvocationList();

((RunDel)da[0])();

((RunDel)da[1])();


--
William Stacey [MVP]

|I want to be able to hand off the inner functionality of a loop to a
| delegate. However, I also need to be able to call one of a number of
| delegates based on the context of the loop ( in this case what level Im
| in in a tree ). Using delegates seems like an easy way to implement all
| of the management, and is well understood.
| Where Im having trouble is invoking a _single_ delegate out of the
| invocation list.
|
| Some simple test code:
|
| class DelegateHolder
| {
| public TestDelegate imATest;
|
| public void RunDelegate()
| {
| // this works
| foreach (TestDelegate wc in imATest.GetInvocationList())
| {
| wc(1);
| }
|
| // this doesnt - runtime exception casting to TestDelegate[]
| TestDelegate[] ds;
| ds = (TestDelegate[])imATest.GetInvocationList();
| ds[0](1);
| ds[1](1);
| ds[2](1);
| }
| }
|
 
H

Helge Jensen

I want to be able to hand off the inner functionality of a loop to a
delegate. However, I also need to be able to call one of a number of
delegates based on the context of the loop ( in this case what level Im
in in a tree ). Using delegates seems like an easy way to implement all
of the management, and is well understood.
Where Im having trouble is invoking a _single_ delegate out of the
invocation list.

Why are you using the delegates invocationlist to represent a list of
delegates?

wouldn't IList<MyDelegate> be much better?
 
M

mmmpie

Why are you using the delegates invocationlist to represent a list of
delegates?

wouldn't IList<MyDelegate> be much better?


I chose to use a delegate because it is a well understood idiom for
someone who wants to pass methods into my class.

Im certainly not adverse to using a collection, but I was trying to do
the c# way.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top