开发者

How to store a function pointer in C#

开发者 https://www.devze.com 2022-12-25 08:28 出处:网络
Let\'s say I want to store a group of function pointers in a List<(*func)>, and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), obje开发者_如何学Pyth

Let's say I want to store a group of function pointers in a List<(*func)>, and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), obje开发者_如何学Pythonct[] params> could I call the func with the parameters? How would I do this?


.NET uses delegates instead of function pointers. You can store a delegate instance like any other kind of object, in a dictionary or otherwise.

See Delegates from the C# Programming Guide on MSDN.


You can absolutely have a dictionary of functions:

Dictionary<string, Action<T>> actionList = new Dictionary<string, Action<T>>();
Dictionary<string, Func<string>> functionList = new Dictionary<string, Func<string>>();

actionList.Add("firstFunction", ()=>{/*do something;*/});
functionList.Add("firstFunction", ()=>{return "it's a string!";});

You can then call the methods like this:

string s = functionList["firstFunction"].Invoke();


Look at the C# documentation on delegates, which is the C# equivalent of a function pointer (it may be a plain function pointer or be curried once to supply the this parameter). There is a lot of information that will be useful to you.


There are a couple ways you could do this. You could do it as others have suggested through the use of delegates. But to get the dictionary to work, they would all need the same signature.

var funcs = new Dictionary<Action<object[]>, object[]>();

Or if they have different signatures you could use the actual reflected method, like the following

var funcs = new Dictionary<MethodInfo, object[]>();


Use ether a delegate or an event (depending on the usage).


If you are only storing event handlers then...

Dictionary<string, EventHandler> dictEvents = new Dictionary<string, EventHandler>();
dictEvents.Add("Event1", someEventHandler);

...

protected void someEventHandler(object sender, EventArgs e)
{
   //Do something.
}

Edit:

  • I put this here because I was searching for a way to do something similar when I found this post. However, the solutions in this post did not quite work for my situation so I figured I would share what did work for me.
0

精彩评论

暂无评论...
验证码 换一张
取 消