I've already checked a few other posts regarding reflection and overloaded methods but could find any help. One post I found was this one, but that didn't help a lot.
I have the following two methods:
1 | public void Delete<T>(T obj) where T : class { ... }
2 | public void Delete<T>(ICollection<T> obj) where T : class { ... }
I'm trying to get method N°1.
I tried the classic GetMethod("Delete") approach, but since there are two methods with this name a Ambiguous-Exception was thrown. I tried specifying the method schema with an additional parameter like GetMethod("Delete", new [] { typeof(Object) }) which didn't find anything (null returned).
I figgured I might as well just loop through all methods and check for the parameters.
I wrote the following method...
public static IEnumerable<MethodInfo> GetMethods(this Type type, String name, Type schemaExclude)
{
IEnumerable<MethodInfo> m = type.GetRuntimeMethods().Where(x => x.Name.Equals(name));
return (from r in m let p = r.GetParameters() where !p.Any(o => schemaExclude.IsAssignableFrom(o.ParameterType)) select r).ToList();
}
... which returns the methods which do not contain a parameter with type schemaExclude.
I called it like this
GetMethods("Delete", typeof(ICollection)) which didn't work as expected.
Apparently ..ICollection'1[T] is not assignable to ICollection. Neither is it to IEnumerable, IEnumerable<> and ICollection<>. I, again, tried it with typeof(Object) which did work but did return both methods (like its supposed to).
What exactly am I missing?
ICollectionparameter, and there were none.Tat compile-time? Then it´s simplyGetMethods("Delete", typeof(ICollection<int>))for example. Otherwise you´d have to build the runtime-type in front usingType.MakeGenericType.Tcould be any of the supported models of my domain. The object I'm handling is a proxy object which means I'm forced to use reflection to access the method with the proper generic type. I could try building the generic type at runtime to getICollection<T>, but I'm not certain that this will match with the schema of the method. Let me try ...typeof(ICollection<>).MakeGenericType(t)where t equals the entity framework model type. My method returned both methods as a result which means that it didn't match the schema.