C#反射 - 将参数转换为类型

时间:2016-07-07 21:55:19

标签: c# reflection

我有一个可以动态调用的ConvertMethods类。

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;
}

可能需要转换的每个值都来自数据库作为字符串。我想动态地将它转换/转换为Invoked方法的参数类型。这就是我所拥有的:

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());
    }
}

我如何将String value转换或转换为paramType包含的任何类型?

1 个答案:

答案 0 :(得分:1)

object convertedParameter = TypeDescriptor.GetConverter(paramType).ConvertFromString(value);

会做你想做的事。