2016-07-07 219 views
-1

我有一个ConvertMethods类可以动态调用。C#反射 - 投射参数到类型

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
object convertedParameter = TypeDescriptor.GetConverter(paramType).ConvertFromString(value); 

会做你想做的。

+0

这只适用于那些有'TypeConverterAttrribute'类型的人,但并非所有人都这么做。 – GreatAndPowerfulOz

+0

不,它适用于很多内置类型 –

+0

当然,所有那些Convert.ChangeType都适用。 –