方法信息和委托

发布于 2024-09-26 17:45:36 字数 1007 浏览 1 评论 0原文

我正在使用 dotnet 2.0

我知道使用 EventInfo 值,您可以循环遍历程序集的类型并查找与 EventInfo 委托定义 ( EventInfo.EventHandlerType ) 匹配的所有方法

有没有办法找出给定 MethodInfo 可以使用哪些可用委托在 Delegate.CreateDelegate() 函数中进行分配,而无需首先循环遍历所有引用的程序集以查找所有委托定义。

或者我是否坚持做以下事情:

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;
}

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亽野灬性zι浪 2024-10-03 17:45:36

听起来确实需要循环遍历所有内容。您说您想找到所有可以工作的“可用”代表。接受委托的函数没有任何指向可以传递给它的方法的链接,因此大型搜索将是找到所有这些方法的唯一方法。

您可以通过仅检查具有公共/内部访问权限的类型来减少搜索时间。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文