I have defined the below concurrent dictionary:(because reflection is slow so cached it)
private static ConcurrentDictionary<Type, MethodInfo> dic = new();
then I wanted to get a method from a type and invoke it.
public void Update(TITarget target)
{
var methodInfo = dic.GetOrAdd(typeof(TITarget), ()=> getMethodInfo);
methodInfo.Invoke(target, new object[] { this });
}
private static MethodInfo getMethodInfo()
{
var types = getInheritanceHierarchy(typeof(TITarget));
var findUpdateMethod = typeof(TITarget)
.GetMethods(BindingFlags.Public | BindingFlags.Instance).
Where(x => x.Name == "Update");
var methodInfo = types.Join(
findUpdateMethod, t => t.Name,
mi => mi.DeclaringType.Name,
(t, mi) => mi)
.First();
return methodInfo;
}
private static IEnumerable<Type> getInheritanceHierarchy(Type type)
{
for (var current = type; current != null; current = current.BaseType)
{
yield return current;
}
}
but i cannot pass a method to the type of MethodInfo and i got the below compile time error:
Severity Code Description Project File Line Suppression State
Error CS1593 Delegate ‘Func<Type, MethodInfo>’ does not take 0 arguments.
how can i fix that issue?
thank you in advance.
>Solution :
dic.GetOrAdd(typeof(TITarget), ()=> getMethodInfo)
You probably want either
dic.GetOrAdd(typeof(TITarget), getMethodInfo())
or, arguably better:
dic.GetOrAdd(typeof(TITarget), key => getMethodInfo(key))
...
private static MethodInfo getMethodInfo(Type type)
{
var types = getInheritanceHierarchy(type);
...
The error message is essentially saying that the compiler guesses you want to call GetOrAdd(TKey, Func<TKey,TValue>), but that obviously needs a lambda with the key as an argument.