2011-07-29 16 views
5

Estoy usando ValueInjecter para la asignación de objetos y estoy intentando inyectar desde un ExpandoObject. Encontré un ejemplo de inyectar desde una dinámica.Inyectar desde ExpandoObject con ValueInjecter

public class Ac 
    { 
     public string Aa { get; set; } 
    } 

    [Test] 
    public void Aa() 
    { 
     var o = new { Aa = "aa" }; 
     dynamic d = o; 
     var a = new Ac{ Aa = "bb" }; 
     a.InjectFrom((object)d); 
     Assert.AreEqual(o.Aa, a.Aa); 
    } 

Pero no he tenido éxito en hacer que funcione con un ExpandoObject. ¿Cómo puedo hacer esto?

+0

Ver [esto q] (http://stackoverflow.com/questions/19529178/recursively-mapping-expandoobject) para una respuesta más completa. – nawfal

Respuesta

7
using System; 
using System.Collections.Generic; 
using System.Dynamic; 
using Omu.ValueInjecter; 

namespace ConsoleApplication7 
{ 
    public class FromExpando : KnownSourceValueInjection<ExpandoObject> 
    { 
     protected override void Inject(ExpandoObject source, object target) 
     { 
      var d = source as IDictionary<string, object>; 
      if (d == null) return; 
      var tprops = target.GetProps(); 

      foreach (var o in d) 
      { 
       var tp = tprops.GetByName(o.Key); 
       if (tp == null) continue; 
       tp.SetValue(target, o.Value); 
      } 
     } 
    } 

    public class Foo 
    { 
     public string Name { get; set; } 
     public int Ace { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      dynamic x = new ExpandoObject(); 
      x.Ace = 1231; 
      x.Name = "hi"; 
      var f = new Foo(); 
      //f.InjectFrom<FromExpando>((object) x); // edit:compilation error 
      new FromExpando().Map((object)x,f); 
      Console.WriteLine(f.Ace); 
      Console.WriteLine(f.Name); 
     } 
    } 
} 
+0

Necesita más trabajo para manejar tipos anidados – nawfal

1

He utilizado el mismo enfoque que Omu publicado leyendo de ExpandoObject that comes from a XML. Como todas las propiedades entra como'string', por lo que he retocado @ respuesta de Omu un poco usando el método'Convert.ChangeType':

public class FromExpando : KnownSourceValueInjection<ExpandoObject> 
{ 
    protected override void Inject(ExpandoObject source, object target) 
    { 
     var d = source as IDictionary<string, object>; 
     if (d == null) return; 
     var tprops = target.GetProps(); 

     foreach (var o in d) 
     { 
      var tp = tprops.GetByName(o.Key); 
      if (tp == null) continue; 

      var newValue = Convert.ChangeType(o.Value, tp.PropertyType); 

      tp.SetValue(target, newValue); 
     } 
    } 
} 
Cuestiones relacionadas