Reputation: 3709
This has been asked before (I think), but looking through the previous answers I still haven't been able to figure out what I need.
Lets say I have a private method like:
private void GenericMethod<T, U>(T obj, U parm1)
Which I can use like so:
GenericMethod("test", 1);
GenericMethod(42, "hello world!");
GenericMethod(1.2345, "etc.");
How can I then pass my GenericMethod
to another method so that I can then call it in that method in a similar way? e.g.:
AnotherMethod("something", GenericMethod);
...
public void AnotherMethod(string parm1, Action<what goes here?> method)
{
method("test", 1);
method(42, "hello world!");
method(1.2345, "etc.");
}
I just can't get my head around this! What do I need to specify as the generic parameters to Action
in AnotherMethod
?!
Upvotes: 10
Views: 7138
Reputation: 31
Consider using an intermediate class (or implement an interface):
class GenericMethodHolder {
public void GenericMethod<T, U>(T obj, U parm1) {...};
}
public void AnotherMethod(string parm1, GenericMethodHolder holder)
{
holder.GenericMethod("test", 1);
holder.GenericMethod(42, "hello world!");
holder.GenericMethod(1.2345, "etc.");
}
Upvotes: 3
Reputation: 9811
Just wanted to post another solution that I found usefull for a while, especially with caching. When I do a Get from Cache, and the cache item doesnt exist, I call the provided function to get the data, cache it and return. But, this can be used in your specific way too.
Your other method would need a signature similar to this, where getItemCallback
is the GenericMethod()
you want to be executed. Example has been cleared down for brevity.
public static T AnotherMethod<T>(string key, Func<T> _genericMethod ) where T : class
{
result = _genericMethod(); //looks like default constructor but the passed in params are in tact.
//... do some work here
return otherData as T;
}
Then you would call your AnotherMethod()
as follows
var result = (Model)AnotherMethod("some string",() => GenericMethod(param1,param2));
I know its about several months later but maybe it will help the next person, as I forgot how to do this and couldn't find any similar answer on SO.
Upvotes: 2
Reputation: 34275
You need to pass into AnotherMethod
not a single delegate of some specific type, but a thing which contructs delegates. I think this can only be done using reflection or dynamic types:
void Run ()
{
AnotherMethod("something", (t, u) => GenericMethod(t, u));
}
void GenericMethod<T, U> (T obj, U parm1)
{
Console.WriteLine("{0}, {1}", typeof(T).Name, typeof(U).Name);
}
void AnotherMethod(string parm1, Action<dynamic, dynamic> method)
{
method("test", 1);
method(42, "hello world!");
method(1.2345, "etc.");
}
Note that (t, u) => GenericMethod(t, u)
cannot be replaced with just GenericMethod
.
Upvotes: 8