Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
hechao committed Mar 14, 2023
1 parent 1f73995 commit 57164d8
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions Source/VSProj/Src/Core/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ public static bool IsAssignable(MethodInfo delegateMethod, MethodInfo method)
}

//适配器的缓存,如果不做缓存,每次都调用IsAssignable一个个的取匹配会非常慢
static Dictionary<Type, MethodInfo> delegateAdptCache = new Dictionary<Type, MethodInfo>();
static Dictionary<string, Dictionary<Type, MethodInfo>> delegateAdptCache =
new Dictionary<string, Dictionary<Type, MethodInfo>>();

/// <summary>
/// 从一个wrapper对象里头,查找能够适配到特定delegate的方法
Expand All @@ -62,20 +63,28 @@ public static bool IsAssignable(MethodInfo delegateMethod, MethodInfo method)
public static Delegate TryAdapterToDelegate(object obj, Type delegateType, string perfix)
{
MethodInfo method;
if (!delegateAdptCache.TryGetValue(delegateType, out method))
if (!delegateAdptCache.TryGetValue(obj.GetType().Assembly.FullName, out var cache))
{
cache = new Dictionary<Type, MethodInfo>();
delegateAdptCache.Add(obj.GetType().Assembly.FullName, cache);
}

if (!cache.TryGetValue(delegateType, out method))
{
MethodInfo delegateMethod = delegateType.GetMethod("Invoke");
var methods = obj.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance
| BindingFlags.DeclaredOnly);
| BindingFlags.DeclaredOnly);
for (int i = 0; i < methods.Length; i++)
{
if (methods[i].Name.StartsWith(perfix) && IsAssignable(delegateMethod, methods[i]))
{
method = methods[i];
delegateAdptCache[delegateType] = method;
cache[delegateType] = method;
}
}
}


if (method == null)
{
return null;
Expand Down

0 comments on commit 57164d8

Please sign in to comment.