MethodInfo and Delegates

好久不见. 提交于 2019-12-11 11:13:26

问题


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:


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.



来源:https://stackoverflow.com/questions/3885834/methodinfo-and-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!