您可以创建组合两个或多个对象的动态对象:
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 。Id
int
viewModel.Id = "42";
ExpandoObject
viewModel.Id
int
product.Id