3

我正在dynamic为我的视图模型使用对象,因为我发现使用 Automapper 之类的东西不必要的开销,并且发现这种方法更加灵活和轻量级。我正在使用即兴界面中的构建器,如下所示:

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

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

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结合反射和迭代所有成员来实现,但我想知道是否有更清洁/更整洁的解决方案。

4

2 回答 2

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或类似的,但无论如何这都不应该是必需的。

于 2011-10-10T22:17:21.593 回答
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";

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

这样做有(至少)一种奇怪的行为:例如,如果有type的Product属性,代码就会成功。但它会将属性设置在. 因此,如果您在那之后尝试检索,它将返回未修改的from 。IdintviewModel.Id = "42";ExpandoObjectviewModel.Idintproduct.Id

于 2011-10-10T14:57:02.350 回答