mercredi 1 juillet 2015

Uniquely identifying a method or constructor using reflection

I need to uniquely identify a method or constructor for any given class so that I can then invoke it at a later stage.

I had thought of using the ConstructorInfo.GetHashCode() and MethodInfo.GetHashCode() methods in the hope that the hashcode would be unique for each object inhertiting MethodBase. While they are unique they also change on each run of the program which means this method is useless to me as I need to persist the objects to database to be able to run it later (i.e. after reboots, service restarts etc).

So far, the only way I can really come up with to uniquely identify the methods and constructors is to

  1. Find a list of matching methods/constructors by name first
  2. Iterate the matching methods/constructors to see which parameter list matches the one I want.

Surely there must be a better way of doing this?

methodParams = null;
constructorInfo = null;

var methods = instanceType.GetMethods().Where(m => m.Name == constructorName);//this is required to handle methods that are overloaded
foreach (var method in methods)
{
    var internalParams = method.GetParameters();
    if (internalParams.Count() == requiredParams.Count())
    {
        var methodParamDict = internalParams.ToDictionary(x => x.Name, x => String.Empty);
        foreach (var requiredParamKey in requiredParams.Keys)
        {
            if (methodParamDict.ContainsKey(requiredParamKey))
            {
                methodParamDict[requiredParamKey] = requiredParams[requiredParamKey];
            }
        }
        if (methodParamDict.All(x => x.Value != String.Empty))
        {
            //set the methodParams to internalParams (i.e. we have found the correct overloaded method)
            methodParams = internalParams;
            constructorInfo = method as ConstructorInfo;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire