jeudi 7 juillet 2016

C# Reflection - Casting Parameter to Type

I have a ConvertMethods class that can be dynamically Invoked.

public class ConvertMethods
{
    public ConvertMethods()
    {
        Type type = typeof(ConvertMethods);
        methodInfos = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
    }

    public Type GetParameterType(string methodName)
    {
        foreach (var method in methodInfos) {
            if (method.Name == methodName) {
                return method.GetParameters()[0].GetType();
            }
        }

        throw new MissingMethodException("ConvertMethods", methodName);
    }

    public Type GetReturnType(string methodName)
    {
        foreach (var method in methodInfos) {
            if (method.Name == methodName) {
                return method.ReturnType;
            }
        }

        throw new MissingMethodException("ConvertMethods", methodName);
    }

    public object InvokeMethod(string methodName, object parameter)
    {
        foreach (var method in methodInfos) {
            if (method.Name == methodName) {
                return InvokeInternal(method, parameter);
            }
        }

        throw new MissingMethodException("ConvertMethods", methodName);
    }

    public static TimeSpan SecondsToTimeSpan(long seconds)
    {
        return TimeSpan.FromSeconds(seconds);
    }

    private object InvokeInternal(MethodInfo method, object parameter)
    {
        return method.Invoke(null, new[] { parameter });
    }

    private MethodInfo[] methodInfos;
}

Potentially, every value that needs to be converted comes from the database as a string. I want to dynamically cast/convert it it to whatever the Parameter Type is of the Invoked method. Here is what I have:

class Program
{
    static void Main(string[] args)
    {
        string methodName = "SecondsToTimeSpan";
        string value = "10";

        ConvertMethods methods = new ConvertMethods();
        Type returnType = methods.GetReturnType(methodName);
        Type paramType = methods.GetParameterType(methodName);

        object convertedParameter = (paramType)value;  // error on this line

        var result =  methods.InvokeMethod(methodName, convertedParameter);

        Console.WriteLine(result.ToString());
    }
}

How can I property convert or convert the String value to whatever type paramType contains?





Aucun commentaire:

Enregistrer un commentaire