MethodInfo and Delegates

2019-08-11 01:02发布

I am using dotnet 2.0

I know that with an EventInfo value, you can loop through an Assembly's Types and find all the methods that match the EventInfo delegate definition ( EventInfo.EventHandlerType )

Is there a way to find out what available delegates a given MethodInfo can be assigned in the Delegate.CreateDelegate() function without first looping through all the referenced assemblies to find all the Delegate definitions.

Or am I stuck doing the following:

public bool MethodInfoDelegateSearch( MethodInfo mi ) {
  System.Collections.Generic.List<Type> delegateTypes = new System.Collections.Generic.List<Type>();
  foreach ( Assembly a in AppDomain.CurrentDomain.GetAssemblies() )
    foreach ( Type t in a.GetTypes() ) {
      if ( t.IsSubclassOf( typeof( Delegate ) ) )
        delegateTypes.Add( t );
    }

  for ( int i = 0; i < delegateTypes.Count; i++ ) {
    Type t = delegateTypes[i];
    /*
     * here is where to attempt match the delegate structure to the MethodInfo
     * I can compare parameters or just attempt to create the delegate
     */
    try {
      Delegate.CreateDelegate( t, mi, true );
      return true;
    } catch {
    }
  }
  return false;
}

1条回答
时光不老,我们不散
2楼-- · 2019-08-11 01:12

It sure sounds like you would need to loop through everything. You say that you want to find all "available" delegates that would work. The function which accepts a delegate doesn't have any links to the methods that could be passed to it, so a large search would be the only way to find them all.

You could reduce the time spent searching by only checking the types with public/internal access.

查看更多
登录 后发表回答