开发者

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:

开发者_Go百科
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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜