Invoke generic delegate [duplicate] - c#

How do I create a Dictionary where I can store functions?
Thanks.
I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:
private void functionName(arg1, arg2, arg3)
{
// code
}
dictionaryName.add("doSomething", functionName);
private void interceptCommand(string command)
{
foreach ( var cmd in dictionaryName )
{
if ( cmd.Key.Equals(command) )
{
cmd.Value.Invoke();
}
}
}
However, the function signature is not always the same, thus having different amount of arguments.

Like this:
Dictionary<int, Func<string, bool>>
This allows you to store functions that take a string parameter and return boolean.
dico[5] = foo => foo == "Bar";
Or if the function is not anonymous:
dico[5] = Foo;
where Foo is defined like this:
public bool Foo(string bar)
{
...
}
UPDATE:
After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.
And here's another alternative:
class Program
{
static void Main()
{
// store
var dico = new Dictionary<int, Delegate>();
dico[1] = new Func<int, int, int>(Func1);
dico[2] = new Func<int, int, int, int>(Func2);
// and later invoke
var res = dico[1].DynamicInvoke(1, 2);
Console.WriteLine(res);
var res2 = dico[2].DynamicInvoke(1, 2, 3);
Console.WriteLine(res2);
}
public static int Func1(int arg1, int arg2)
{
return arg1 + arg2;
}
public static int Func2(int arg1, int arg2, int arg3)
{
return arg1 + arg2 + arg3;
}
}
With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.

However, the function signature is not
always the same, thus having different
amount of arguments.
Let's start with a few functions defined like this:
private object Function1() { return null; }
private object Function2(object arg1) { return null; }
private object Function3(object arg1, object arg3) { return null; }
You really have 2 viable options at your disposal:
1) Maintain type-safety by having clients call your function directly.
This is probably the best solution, unless you have very good reasons for breaking from this model.
When you talk about wanting to intercept function calls, it sounds to me like you're trying to re-invent virtual functions. There's a boat load of ways to get this sort of functionality out of the box, such as inheriting from a base class an overriding its functions.
It sounds to me like you want a class that's more of a wrapper than a derived instance of a base class, so do something like this:
public interface IMyObject
{
object Function1();
object Function2(object arg1);
object Function3(object arg1, object arg2);
}
class MyObject : IMyObject
{
public object Function1() { return null; }
public object Function2(object arg1) { return null; }
public object Function3(object arg1, object arg2) { return null; }
}
class MyObjectInterceptor : IMyObject
{
readonly IMyObject MyObject;
public MyObjectInterceptor()
: this(new MyObject())
{
}
public MyObjectInterceptor(IMyObject myObject)
{
MyObject = myObject;
}
public object Function1()
{
Console.WriteLine("Intercepted Function1");
return MyObject.Function1();
}
public object Function2(object arg1)
{
Console.WriteLine("Intercepted Function2");
return MyObject.Function2(arg1);
}
public object Function3(object arg1, object arg2)
{
Console.WriteLine("Intercepted Function3");
return MyObject.Function3(arg1, arg2);
}
}
2) OR map the input of your functions to a common interface.
This might work if all of your functions are related. For example, if you're writing a game, and all the functions do something to some part of the player or player's inventory. You'd end up with something like this:
class Interceptor
{
private object function1() { return null; }
private object function2(object arg1) { return null; }
private object function3(object arg1, object arg3) { return null; }
Dictionary<string, Func<State, object>> functions;
public Interceptor()
{
functions = new Dictionary<string, Func<State, object>>();
functions.Add("function1", state => function1());
functions.Add("function2", state => function2(state.arg1, state.arg2));
functions.Add("function3", state => function3(state.arg1, state.are2, state.arg3));
}
public object Invoke(string key, object state)
{
Func<object, object> func = functions[key];
return func(state);
}
}

Define the dictionary and add the function reference as the value, using System.Action as the type:
using System.Collections;
using System.Collections.Generic;
public class Actions {
public Dictionary<string, System.Action> myActions = new Dictionary<string, System.Action>();
public Actions() {
myActions ["myKey"] = TheFunction;
}
public void TheFunction() {
// your logic here
}
}
Then invoke it with:
Actions.myActions["myKey"]();

Hey, I hope this helps. What language are you coming from?
internal class ForExample
{
void DoItLikeThis()
{
var provider = new StringMethodProvider();
provider.Register("doSomethingAndGetGuid", args => DoSomeActionWithStringToGetGuid((string)args[0]));
provider.Register("thenUseItForSomething", args => DoSomeActionWithAGuid((Guid)args[0],(bool)args[1]));
Guid guid = provider.Intercept<Guid>("doSomethingAndGetGuid", "I don't matter except if I am null");
bool isEmpty = guid == default(Guid);
provider.Intercept("thenUseItForSomething", guid, isEmpty);
}
private void DoSomeActionWithAGuid(Guid id, bool isEmpty)
{
// code
}
private Guid DoSomeActionWithStringToGetGuid(string arg1)
{
if(arg1 == null)
{
return default(Guid);
}
return Guid.NewGuid();
}
}
public class StringMethodProvider
{
private readonly Dictionary<string, Func<object[], object>> _dictionary = new Dictionary<string, Func<object[], object>>();
public void Register<T>(string command, Func<object[],T> function)
{
_dictionary.Add(command, args => function(args));
}
public void Register(string command, Action<object[]> function)
{
_dictionary.Add(command, args =>
{
function.Invoke(args);
return null;
} );
}
public T Intercept<T>(string command, params object[] args)
{
return (T)_dictionary[command].Invoke(args);
}
public void Intercept(string command, params object[] args)
{
_dictionary[command].Invoke(args);
}
}

The following scenario would allow you to use a dictionary of elements to send in as input parameters and get the same as the output parameters.
First add the following line at the top:
using TFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IDictionary<string, object>>;
Then inside your class, define the dictionary as follows:
private Dictionary<String, TFunc> actions = new Dictionary<String, TFunc>(){
{"getmultipledata", (input) =>
{
//DO WORKING HERE
return null;
}
},
{"runproc", (input) =>
{
//DO WORKING HERE
return null;
}
}
};
This would allow you to run these anonymous functions with a syntax similar to this:
var output = actions["runproc"](inputparam);

Why not use params object[] list for method parameters and do some validation inside either your methods (or calling logic), It will allow for a variable number of parameters.

Related

Create a list of C# Funcs with different parameter types

I want to be able to create multiple Funcs each of which takes in an instance of a type and returns the same type e.g.:
Func<Foo, Foo>
Func<Bar, Bar>
And then add these to a List (or perhaps to a Dictionary, keyed by the type that the Func handles).
Then given any instance y (the type of which is not known at compile time), I want to retrieve and invoke the Func that will work for on y.
Is what I am asking for even possible?
You can create a dictionary of delegates. Use the type as key.
Dictionary<Type, Delegate> _dictionary = new();
And we will need a method to add delegates:
bool Add<T>(Func<T, T> func)
{
return _dictionary.TryAdd(typeof(T), func);
}
And one to call them:
static T DoIt<T>(T t)
{
if (_dictionary.TryGetValue(typeof(T), out var func))
{
return ((Func<T, T>)func).Invoke(t);
}
throw new NotImplementedException();
}
Working example:
using System;
using System.Collections.Generic;
public class Program
{
private static Dictionary<Type, Delegate> _dictionary = new();
public static void Main()
{
Add<String>(InternalDoIt);
Add<int>(InternalDoIt);
DoIt("Hello World"); // Outputs "Hello World"
DoIt(1); // Outputs "1"
DoIt(DateTime.Now); // Throws NotImplementException
}
static bool Add<T>(Func<T, T> func)
{
return _dictionary.TryAdd(typeof(T), func);
}
static T DoIt<T>(T t)
{
if (_dictionary.TryGetValue(typeof(T), out var func))
{
return ((Func<T, T>)func).Invoke(t);
}
throw new NotImplementedException();
}
static string InternalDoIt(string str){
Console.WriteLine(str);
return str;
}
static int InternalDoIt(int i) {
Console.WriteLine(i);
return i;
}
}
No puppies or kitties died in the making of this answer.
Have you considered the following approach?
using System;
public class Program
{
public static void Main()
{
DoIt("Hello World");
DoIt(1);
DoIt(DateTime.Now);
}
static dynamic DoIt(dynamic t)
{
return InternalDoIt(t);
}
static object InternalDoIt(object obj) => throw new NotImplementedException();
static string InternalDoIt(string str){
Console.WriteLine(str);
return str;
}
static int InternalDoIt(int i) {
Console.WriteLine(i);
return i;
}
}
https://dotnetfiddle.net/RoXK0M

C# Dynamic Function AmbigiousMatchException?

I'm getting an AmbigiousMatchException for a function calling Type.GetMethod() even though everything looks pretty much correct.
public partial class IBaseEvent
{
private Dictionary<int, Func<object[], object>> funcs = new Dictionary<int,Func<object[],object>>();
private Dictionary<int, object[]> func_args = new Dictionary<int,object[]>();
public void Execute()
{
int exp = 0;
foreach(var func in funcs)
{
exp = func.GetHashCode();
func.Value.DynamicInvoke(func_args[exp]);
}
}
public void AddFunction(Type T, dynamic sFunc, params object[] parameters)
{
funcs.Add(T.GetHashCode(), new Func<object[],object>(T.GetMethod(sFunc)));
func_args.Add(T.GetHashCode(), parameters);
}
}
public class DummyEvent : IBaseEvent
{
private string EventType = "DUMMY_EVENT";
public DummyEvent()
{
object[] parm = new object[3];
parm[0] = Logging.LOG_TYPE.DEBUG;
parm[1] = "Hello World from DummyEvent! TypeCode: {0}";
parm[2] = typeof(DummyEvent).GetType().GUID;
AddFunction(typeof(Logging.LoggingFactory), "WriteToLog", parm);
}
}
Errors on AddFunction(typeof(Logging.LoggingFactory), "WriteToLog", parm);
What am I doing wrong? and how can I correct this?
Based on the error message, I suspect that you may already have a function WriteToLog in LoggingFactory or its inheritance chain.
It seems like you are unnecessarily complicating stuff. Both the function and its argument are known whenever you are adding it to the list. Have you considering using anonymous functions like so. As an example I have wrapped the this object.. the string argument in this example. DynamicInvoke will be considerably slower as well.
Also two different Types can return the same GetHashCode which depending on your particular needs may or may not matter.
public partial class IBaseEvent
{
private Dictionary<int, Action> funcs = new Dictionary<int, Action>();
public void Execute()
{
foreach (var func in funcs.Values)
{
func();
}
}
public void AddFunction(Type t, Action ff)
{
funcs.Add(t.GetHashCode(), ff);
}
}
public class DummyEvent : IBaseEvent
{
private string EventType = "DUMMY_EVENT";
private void DoSomething(string x)
{
Console.WriteLine(x);
}
public DummyEvent()
{
Action temp = () =>
{
DoSomething("Hello World from DummyEvent! TypeCode");
};
AddFunction(typeof(Logging), temp);
}
}
If type is strictly not needed you can further simply it like so
public partial class IBaseEvent
{
public Action MyAction;
public void Execute()
{
MyAction();
}
public void AddFunction(Action ff)
{
MyAction += ff;
}
}

Is it legal to assign by ref to a field using IL?

There is as far as I know no way to interact with reference types in Expression trees. (e.g. nothing emits a stind.* or a ldind.* opcode).
I'm working on a bit of a rewriter to get around this annoyance. Since I'm building a new type that has the method body replaced with delegate invocations (to get around the fact that CompileToMethod can only do static methods that can't interact with new members). For by-ref and out parameters, I thought I'd replace their usages with StrongBox<T>.
So if I came across a method that has a signature that looks like this::
public class SomeClass
{
public virtual bool SomeMethod(string arg1,ref int arg2)
{
}
}
The override, the callbase method, and the delegate field I generate will look like this::
public class SomeClass<1> : SomeClass
{
private static bool SomeMethod<0>(
SomeClass target,string arg1,StrongBox<int> arg2)
{
return call target.SomeMethod(arg1,ref arg2.Value)
}
private Func<SomeClass,string,StrongBox<int>,bool> <0>SomeMethod;
public override bool SomeMethod(string arg1,ref int arg2)
{
StrongBox<int> box = new StrongBox<int>();
box.Value = arg2;
bool retVal = <0>SomeMethod.Invoke(this,arg1,box);
arg2 = box.Value;
return retVal;
}
}
However, this is quite a lot of code to perform this conversion, for each parameter it introduces a lot of complexity. It would be much easier when I perform the setting of box.Value = arg2, if I could do something like &box.Value = &arg2 that is assign it's address to the address of arg2 as it stands. That way when the delegate performs a mutation on the value field the changes are forwarded. Doing this means I don't need to have to have a variable to hold the return value, and I don't need to perform a reference value update.
Alternatively, if there is a way to perform assign-by-ref semantics with Expression trees, I'm all ears of course.
Not sure if I really understand but maybe this is a solution:
class Program
{
public class SomeClass
{
private readonly int _n;
public SomeClass(int n) { _n = n; }
public virtual bool SomeMethod(string arg1, ref int arg2) {
if (String.IsNullOrWhiteSpace(arg1)) return false;
arg2 += arg1.Length + _n;
return true;
}
}
private delegate bool SomeDelegate(SomeClass that, string arg1, ref int arg2);
static void Main(string[] args) {
var instance = Expression.Parameter(typeof (SomeClass), "that");
var arg1Param = Expression.Parameter(typeof(string), "arg1");
var arg2Param = Expression.Parameter(typeof (int).MakeByRefType(), "arg2");
var someMethodInfo = typeof (SomeClass).GetMethod("SomeMethod");
var lambda = Expression.Lambda<SomeDelegate>(Expression.Call(instance, someMethodInfo, arg1Param, arg2Param), instance, arg1Param, arg2Param);
var someDelegate =lambda.Compile();
var myClass = new SomeClass(2);
var arg1 = "yup";
var arg2 = 1;
var result = someDelegate(myClass, arg1, ref arg2);
if(arg2 != 6) throw new Exception("Bad!");
Console.WriteLine("works...");
}
}
The important bit I think is typeof (int).MakeByRefType() .

C# Store functions in a Dictionary

How do I create a Dictionary where I can store functions?
Thanks.
I have about 30+ functions which can be executed from the user. I want to be able to execute the function this way:
private void functionName(arg1, arg2, arg3)
{
// code
}
dictionaryName.add("doSomething", functionName);
private void interceptCommand(string command)
{
foreach ( var cmd in dictionaryName )
{
if ( cmd.Key.Equals(command) )
{
cmd.Value.Invoke();
}
}
}
However, the function signature is not always the same, thus having different amount of arguments.
Like this:
Dictionary<int, Func<string, bool>>
This allows you to store functions that take a string parameter and return boolean.
dico[5] = foo => foo == "Bar";
Or if the function is not anonymous:
dico[5] = Foo;
where Foo is defined like this:
public bool Foo(string bar)
{
...
}
UPDATE:
After seeing your update it seems that you don't know in advance the signature of the function you would like to invoke. In .NET in order to invoke a function you need to pass all the arguments and if you don't know what the arguments are going to be the only way to achieve this is through reflection.
And here's another alternative:
class Program
{
static void Main()
{
// store
var dico = new Dictionary<int, Delegate>();
dico[1] = new Func<int, int, int>(Func1);
dico[2] = new Func<int, int, int, int>(Func2);
// and later invoke
var res = dico[1].DynamicInvoke(1, 2);
Console.WriteLine(res);
var res2 = dico[2].DynamicInvoke(1, 2, 3);
Console.WriteLine(res2);
}
public static int Func1(int arg1, int arg2)
{
return arg1 + arg2;
}
public static int Func2(int arg1, int arg2, int arg3)
{
return arg1 + arg2 + arg3;
}
}
With this approach you still need to know the number and type of parameters that need to be passed to each function at the corresponding index of the dictionary or you will get runtime error. And if your functions doesn't have return values use System.Action<> instead of System.Func<>.
However, the function signature is not
always the same, thus having different
amount of arguments.
Let's start with a few functions defined like this:
private object Function1() { return null; }
private object Function2(object arg1) { return null; }
private object Function3(object arg1, object arg3) { return null; }
You really have 2 viable options at your disposal:
1) Maintain type-safety by having clients call your function directly.
This is probably the best solution, unless you have very good reasons for breaking from this model.
When you talk about wanting to intercept function calls, it sounds to me like you're trying to re-invent virtual functions. There's a boat load of ways to get this sort of functionality out of the box, such as inheriting from a base class an overriding its functions.
It sounds to me like you want a class that's more of a wrapper than a derived instance of a base class, so do something like this:
public interface IMyObject
{
object Function1();
object Function2(object arg1);
object Function3(object arg1, object arg2);
}
class MyObject : IMyObject
{
public object Function1() { return null; }
public object Function2(object arg1) { return null; }
public object Function3(object arg1, object arg2) { return null; }
}
class MyObjectInterceptor : IMyObject
{
readonly IMyObject MyObject;
public MyObjectInterceptor()
: this(new MyObject())
{
}
public MyObjectInterceptor(IMyObject myObject)
{
MyObject = myObject;
}
public object Function1()
{
Console.WriteLine("Intercepted Function1");
return MyObject.Function1();
}
public object Function2(object arg1)
{
Console.WriteLine("Intercepted Function2");
return MyObject.Function2(arg1);
}
public object Function3(object arg1, object arg2)
{
Console.WriteLine("Intercepted Function3");
return MyObject.Function3(arg1, arg2);
}
}
2) OR map the input of your functions to a common interface.
This might work if all of your functions are related. For example, if you're writing a game, and all the functions do something to some part of the player or player's inventory. You'd end up with something like this:
class Interceptor
{
private object function1() { return null; }
private object function2(object arg1) { return null; }
private object function3(object arg1, object arg3) { return null; }
Dictionary<string, Func<State, object>> functions;
public Interceptor()
{
functions = new Dictionary<string, Func<State, object>>();
functions.Add("function1", state => function1());
functions.Add("function2", state => function2(state.arg1, state.arg2));
functions.Add("function3", state => function3(state.arg1, state.are2, state.arg3));
}
public object Invoke(string key, object state)
{
Func<object, object> func = functions[key];
return func(state);
}
}
Define the dictionary and add the function reference as the value, using System.Action as the type:
using System.Collections;
using System.Collections.Generic;
public class Actions {
public Dictionary<string, System.Action> myActions = new Dictionary<string, System.Action>();
public Actions() {
myActions ["myKey"] = TheFunction;
}
public void TheFunction() {
// your logic here
}
}
Then invoke it with:
Actions.myActions["myKey"]();
Hey, I hope this helps. What language are you coming from?
internal class ForExample
{
void DoItLikeThis()
{
var provider = new StringMethodProvider();
provider.Register("doSomethingAndGetGuid", args => DoSomeActionWithStringToGetGuid((string)args[0]));
provider.Register("thenUseItForSomething", args => DoSomeActionWithAGuid((Guid)args[0],(bool)args[1]));
Guid guid = provider.Intercept<Guid>("doSomethingAndGetGuid", "I don't matter except if I am null");
bool isEmpty = guid == default(Guid);
provider.Intercept("thenUseItForSomething", guid, isEmpty);
}
private void DoSomeActionWithAGuid(Guid id, bool isEmpty)
{
// code
}
private Guid DoSomeActionWithStringToGetGuid(string arg1)
{
if(arg1 == null)
{
return default(Guid);
}
return Guid.NewGuid();
}
}
public class StringMethodProvider
{
private readonly Dictionary<string, Func<object[], object>> _dictionary = new Dictionary<string, Func<object[], object>>();
public void Register<T>(string command, Func<object[],T> function)
{
_dictionary.Add(command, args => function(args));
}
public void Register(string command, Action<object[]> function)
{
_dictionary.Add(command, args =>
{
function.Invoke(args);
return null;
} );
}
public T Intercept<T>(string command, params object[] args)
{
return (T)_dictionary[command].Invoke(args);
}
public void Intercept(string command, params object[] args)
{
_dictionary[command].Invoke(args);
}
}
The following scenario would allow you to use a dictionary of elements to send in as input parameters and get the same as the output parameters.
First add the following line at the top:
using TFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IDictionary<string, object>>;
Then inside your class, define the dictionary as follows:
private Dictionary<String, TFunc> actions = new Dictionary<String, TFunc>(){
{"getmultipledata", (input) =>
{
//DO WORKING HERE
return null;
}
},
{"runproc", (input) =>
{
//DO WORKING HERE
return null;
}
}
};
This would allow you to run these anonymous functions with a syntax similar to this:
var output = actions["runproc"](inputparam);
Why not use params object[] list for method parameters and do some validation inside either your methods (or calling logic), It will allow for a variable number of parameters.

Is it possible to send an Object's Method to a Function?

I am wondering if it is possible (and what the syntax would be) to send an object's method to a function.
Example:
Object "myObject" has two methods "method1" and "method2"
I would like to have a function along the lines of:
public bool myFunc(var methodOnObject)
{
[code here]
var returnVal = [run methodOnObject here]
[code here]
return returnVal;
}
So that in another function I could do something like
public void overallFunction()
{
var myObject = new ObjectItem();
var method1Success = myFunc(myObject.method1);
var method2Success = myFunc(myObject.method2);
}
Yes, you need to use a delegate. Delegates are fairly analogous to function pointers in C/C++.
You'll first need to declare the signature of the delegate. Say I have this function:
private int DoSomething(string data)
{
return -1;
}
The delegate declaration would be...
public delegate int MyDelegate(string data);
You could then declare myFunc in this way..
public bool myFunc(MyDelegate methodOnObject)
{
[code here]
int returnValue = methodOnObject("foo");
[code here]
return returnValue;
}
You can then call it in one of two ways:
myFunc(new MyDelegate(DoSomething));
Or, in C# 3.0 and later, you can use the shorthand of...
myFunc(DoSomething);
(It just wraps the provided function in the default constructor for that delegate automatically. The calls are functionally identical).
If you don't care to actually create a delegate or actual function implementation for simple expressions, the following will work in C# 3.0 as well:
public bool myFunc(Func<string, int> expr)
{
[code here]
int returnValue = methodOnObject("foo");
[code here]
return returnValue;
}
Which could then be called like so:
myFunc(s => return -1);
Is there really a need for explicit delegates? Maybe this approach would help you:
private class MyObject
{
public bool Method1() { return true; } // Your own logic here
public bool Method2() { return false; } // Your own logic here
}
private static bool MyFunction(Func<bool> methodOnObject)
{
bool returnValue = methodOnObject();
return returnValue;
}
private static void OverallFunction()
{
MyObject myObject = new MyObject();
bool method1Success = MyFunction(myObject.Method1);
bool method2Success = MyFunction(myObject.Method2);
}
Yes, using delegates ..
Here is an example..
delegate string myDel(int s);
public class Program
{
static string Func(myDel f)
{
return f(2);
}
public static void Main()
{
Test obj = new Test();
myDel d = obj.func;
Console.WriteLine(Func(d));
}
}
class Test
{
public string func(int s)
{
return s.ToString();
}
}

Categories