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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With