Mark Nicholls <[EMAIL PROTECTED]> wrote:
> class Bar
> {
> int Foo<X>(X x);
> }
>
> how do I define a single delegate that can refer to Foo?
>
> delegate int FooDelegate<X>(X x);
Sure, that'll work:
---8<---
using System;
class App
{
int Foo<X>(X x)
{
return 0;
}
delegate int FooDelegate<X>(X x);
void P<T>()
{
FooDelegate<T> f = Foo<T>; // works just fine
}
static void Main(string[] args)
{
}
}
--->8---
What you can't do is create a delegate to an uninstantiated generic
method in non-generic code - for one thing, what would the type of the
delegate be? How could you call it, when it expects a value of type X,
and you've got no way of specifying the type X for a normal delegate?
FooDelegate f = Foo<>;
f(???)
If you want to be able to pass around something which can be called, and
resolved (i.e. type arguments bound) later, try getting the MethodInfo
for Bar.Foo<>, and passing that around instead. You can call
MethodInfo.MakeGenericMethod to supply the type arguments, and use
Delegate.CreateDelegate to turn it into something that's more
efficiently callable than via reflection.
Ah, I just saw in your later message that you want a method pointer
(i.e. a delegate) which magically instantiates the target method when
you supply a type argument. That can be emulated via the MethodInfo
approach described in the previous paragraph. With a bit of moderately
clever design, you could create set of related reusable generic types,
all with different arity of their Invoke methods, that solves this
problem in a totally general way.
-- Barry
--
http://barrkel.blogspot.com/
===================================
This list is hosted by DevelopMentorĀ® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com