2010-10-24 13 views
60
foreach (var filter in filters) 
{ 
    var filterType = typeof(Filters); 
    var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static); 
    if (method != null) 
    { 
     var parameters = method.GetParameters(); 
     Type paramType = parameters[0].ParameterType; 
     value = (string)method.Invoke(null, new[] { value }); 
    } 
} 

¿Cómo puedo convertir value en paramType? value es un string, paramType probablemente solo sea un tipo básico como int, string, o tal vez float. Estoy de acuerdo con que arroje una excepción si no es posible la conversión.¿Convertir variable a tipo solo conocido en tiempo de ejecución?

+1

posible duplicado de [? Cómo las operaciones de búsqueda y de invocar un .Net TypeConverter para un tipo particular] (http://stackoverflow.com/questions/956076/how-to-lookup-and-invoke -a-net-tipo-convertidor-para-un-tipo-particular) –

+0

Posible duplicado de [¿Cómo buscar e invocar .Net TypeConverter para un tipo particular?] (http://stackoverflow.com/questions/956076/how- to-lookup-and-invoke-a-net-typeconverter-for-a-particular-type) –

Respuesta

62

Los tipos que está utilizando implementan IConvertible. Como tal, puede usar ChangeType.

value = Convert.ChangeType(method.Invoke(null, new[] { value }), paramType); 
+7

impresionante ... en una sola línea. var value = Convert.ChangeType (objectValue, objectType); – Rigin

12

Puede ir dinámico; por ejemplo:

using System; 

namespace TypeCaster 
{ 
    class Program 
    { 
     internal static void Main(string[] args) 
     { 
      Parent p = new Parent() { name = "I am the parent", type = "TypeCaster.ChildA" }; 
      dynamic a = Convert.ChangeType(new ChildA(p.name), Type.GetType(p.type)); 
      Console.WriteLine(a.Name); 

      p.type = "TypeCaster.ChildB"; 
      dynamic b = Convert.ChangeType(new ChildB(p.name), Type.GetType(p.type)); 
      Console.WriteLine(b.Name); 
     } 
    } 

    internal class Parent 
    { 
     internal string type { get; set; } 
     internal string name { get; set; } 

     internal Parent() { } 
    } 

    internal class ChildA : Parent 
    { 
     internal ChildA(string name) 
     { 
      base.name = name + " in A"; 
     } 

     public string Name 
     { 
      get { return base.name; } 
     } 
    } 

    internal class ChildB : Parent 
    { 
     internal ChildB(string name) 
     { 
      base.name = name + " in B"; 
     } 

     public string Name 
     { 
      get { return base.name; } 
     } 
    } 
} 
Cuestiones relacionadas