使用ValueInjecter从ExpandoObject注入

时间:2011-07-29 22:10:35

标签: c# mapping valueinjecter

我正在使用ValueInjecter进行对象映射,我正在尝试从ExpandoObject中注入。我找到了一个从动态注入的例子。

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

但是我没有成功地使用ExpandoObject。我怎么能这样做?

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

我使用了与Omu发布的ExpandoObject that comes from a XML阅读相同的方法。由于所有属性都是“串”,所以我使用'Convert.ChangeType'方法稍微调整了@ Omu的答案:

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