这并不能完全解决您的场景,但是使用 DynamicObject 实现作为对象周围的装饰器怎么样?它将允许您访问原始对象以及其他属性。有点像 ExpandoObject 但从您自己的实例数据开始。
像这样的东西:
public class Expando : DynamicObject
{
public dynamic Instance;
Dictionary<string, dynamic> ExtraProperties = new Dictionary<string, dynamic>();
public Expando(object instance)
{
Instance = instance;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
try
{
result = ReflectionUtils.GetProperty(Instance, binder.Name);
return true;
}
catch
{
if (ExtraProperties.Keys.Contains(binder.Name))
{
result = ExtraProperties[binder.Name];
return true;
}
}
result = null;
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
try
{
ReflectionUtils.SetProperty(Instance, binder.Name, value);
}
catch (Exception ex)
{
ExtraProperties[binder.Name] = value;
}
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
try
{
result = ReflectionUtils.CallMethod(Instance, binder.Name, args);
return true;
}
catch
{}
result = null;
return false;
}
}
不幸的是,它并没有解决您的强类型/界面要求,并且考虑到此处的反射使用(来自https://github.com/RickStrahl/Westwind.Utilities/blob/master/Westwind.实用程序/实用程序/ReflectionUtils.cs)