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



我有一个可以动态调用的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;
}

可能需要转换的每个值都以字符串的形式来自数据库。 我想动态地将其转换/转换为调用方法的任何参数类型。 这是我所拥有的:

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属性转换或转换为参数类型包含的任何类型?

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

会做你想做的事。

相关内容

  • 没有找到相关文章

最新更新