2016-07-07 6 views
-1

私は動的に呼び出すことができるConvertMethodsクラスを持っています。C#Reflection - 型へのキャストパラメータ

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

Iプロパティが変換またはString valueは、paramTypeが含まれているものは何でも型に変換できますか?

答えて

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

あなたが望むことをします。

+0

これは、すべてではない「TypeConverterAttrribute」を持つ型に対してのみ機能します。 – GreatAndPowerfulOz

+0

いいえ、多くの組み込み型でも動作します。 –

+0

確かに、Convert.ChangeTypeが動作するものはすべてです。 –

関連する問題