将静态类型对象展开为动态对象

时间:2011-10-10 00:35:46

标签: c# dynamic impromptu-interface

我正在为我的视图模型使用dynamic个对象,因为我发现使用像Automapper之类的东西所需的开销,并且发现这种方法更加灵活和轻量级。我正在使用impromptu-interface中的构建器:

private dynamic New = Builder.New();

private dynamic GetViewModel(Product p)
{
    var viewModel = New.Product( id : p.Id, name : p.Name );
    viewModel.AdditionalProperty = "some additional data";
    return viewModel;
}

在某些情况下,“扩展”实际对象会更好,然后逐个重新映射所有属性,类似于使用jQuery.extend()

在JavaScript中的操作方式
private dynamic GetViewModel(Product p)
{
    var viewModel = //create base dynamic object, that has all the members of p.
    viewModel.AdditionalProperty = "some additional data";
    return viewModel;
}

这应该可以使用ExpandoObject结合反射并迭代所有成员来实现,但我想知道是否有更清洁/更整洁的解决方案。

2 个答案:

答案 0 :(得分:4)

我最终实现了这样:

public class ExpandedObject : DynamicObject
{
    private readonly IDictionary<string, object> expando = new ExpandoObject();

    public ExpandedObject(object o)
    {            
        foreach (var propertyInfo in o.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
        {
            this.expando[propertyInfo.Name] = Impromptu.InvokeGet(o, propertyInfo.Name);
        }
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {            
        return this.expando.TryGetValue(binder.Name, out result);
    }

    public override bool  TrySetMember(SetMemberBinder binder, object value)
    {
        this.expando[binder.Name] = value;
        return true;
    }
}

和测试:

[TestFixture]
public class ExpandedObjectTest
{
    [Test]
    public void Can_add_new_properties_to_expanded_object()
    {
        dynamic expanded = new ExpandedObject(new object());
        var data = "some additional data";
        expanded.data = data;
        Assert.AreEqual(data, expanded.data);
    }

    [Test]
    public void Copies_existing_properties()
    {            
        var obj = new { id = 5 };            
        dynamic expanded = new ExpandedObject(obj);            
        Assert.AreEqual(obj.id, expanded.id);            
    }
}

这会使用Impromptu.InvokeGet()代替PropertyInfo.GetValue(),因为Impromptu.InvokeGet()使用DLR,因此比使用我的测试反射快2.5倍。总的来说,它的工作速度相当快,而且最多10,000个对象的开销几乎是不存在的。

我应该注意,这不会扩展其他ExpandoObject或类似内容,但无论如何这不应该是必要的。

答案 1 :(得分:1)

您可以创建组合两个或多个对象的动态对象:

class CombineDynamic : DynamicObject
{
    private readonly object[] m_objects;

    public CombineDynamic(params object[] objects)
    {
        m_objects = objects;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var callSite = CallSite<Func<CallSite, object, object>>.Create(binder);

        foreach (var o in m_objects)
        {
            try
            {
                result = callSite.Target(callSite, o);
                return true;
            }
            catch (RuntimeBinderException)
            {}
        }

        return base.TryGetMember(binder, out result);
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        // the binder from argument uses compile time type from call site,
        // which is object here; because of that, setting of properties that 
        // aren't of type object wouldn't work if we used that binder directly
        var fixedBinder = Binder.SetMember(
            CSharpBinderFlags.None, binder.Name, typeof(CombineDynamic),
            new[]
            {
                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)
            });

        var callSite =
            CallSite<Action<CallSite, object, object>>.Create(fixedBinder);

        foreach (var o in m_objects)
        {
            try
            {
                callSite.Target(callSite, o, value);
                return true;
            }
            catch (RuntimeBinderException)
            {}
        }

        return base.TrySetMember(binder, value);
    }
}

并像这样使用它:

dynamic viewModel = new CombineDynamic(product, new ExpandoObject());
viewModel.AdditionalProperty = "additional data";

当您动态获取或设置属性时,它首先尝试在第一个对象上执行该操作,然后在第二个对象上执行此操作,直到成功为止。

这样做(至少)有一个奇怪的行为:例如,如果Product具有Id类型的属性int,则代码viewModel.Id = "42";会成功。但它会在ExpandoObject上设置属性。因此,如果您之后尝试检索viewModel.Id,则会从int返回product.Id,但未修改。{/ p>