Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Action.ToString() return anything other than "System.Action"?

I'm programming in Unity, using an Action event to hold a bunch of other Action delegates, in order to hook non-Monobehaviour objects into the Update() system. I'd like to be able to print the names of the actions to the Debug console, but using something like:

Delegate[] actions = updateActions.GetInvocationList();
foreach ( Delegate del in actions ) {
    Debug.Log( del.ToString() );
}

... just returns "System.Action". I've tried also (del as Action).ToString() with no luck.

like image 627
Robin King Avatar asked Oct 13 '11 16:10

Robin King


2 Answers

You can use the Method property to get a MethodInfo which should have a useful name.

Delegate[] actions = updateActions.GetInvocationList();
foreach ( Delegate del in actions )
{
    Debug.Log( del.Method.ReflectedType.FullName + "." + del.Method.Name );
}

You can use del.Method.ToString() if you want the signature or del.Method.Name if you only want the name. del.Method.ReflectedType.FullName gives you the type name.

For lambdas/anonymous methods the name might not be too useful since they only have a compiler generated name. In the current implementation the name of a lambda is something like <Main>b__0 where Main is the name of the method that contains the lambda. Together with the type name this should give you a decent idea which lambda it is.

like image 114
CodesInChaos Avatar answered Sep 30 '22 01:09

CodesInChaos


If you mean that you declare a delegate

var foo = new Action(() => { /* do something */ });

and you want to retrieve the word "foo" later, you're out of luck. To get that behavior you'll have to consume the declaration as an expression tree and parse out foo yourself.

like image 39
mqp Avatar answered Sep 30 '22 02:09

mqp