public class MyDynamicObject : DynamicObject
{ public MyDynamicObject(ObjectId oid) { ObjectId = oid; } public ObjectId ObjectId { get; private set; } private DBObject dbobject; public DBObject DBObject { get { if (dbobject == null) dbobject = ObjectId.GetObject(OpenMode.ForRead); return dbobject; } } public override bool TryGetMember(GetMemberBinder binder, out object result) { try { object xxx = DBObject.GetType().InvokeMember(binder.Name, BindingFlags.GetProperty, null, DBObject, null); result = xxx == null ? null : promoteId(xxx); return true; } catch { result = null; return false; } } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { try { object xxx = DBObject.GetType().InvokeMember(binder.Name, BindingFlags.InvokeMethod, null, DBObject, args); result = xxx == null ? null : promoteId(xxx); return true; } catch { result = null; return false; } } public override bool TrySetMember(SetMemberBinder binder, object value) { try { DBObject.GetType().InvokeMember(binder.Name, BindingFlags.SetProperty, null, DBObject, new object[] { value }); return true; } catch { return false; } } public override bool TryConvert(ConvertBinder binder, out object result) { try { if (binder.ReturnType == typeof(IEnumerable)) { result = testIEnum(DBObject); } else if (binder.ReturnType == typeof(ObjectId)) { result = ObjectId; } else { result = DBObject; } return true; } catch { result = null; return false; } } object promoteId(object value) { if (!(value is ObjectId)) return value; return new MyDynamicObject((ObjectId)value); } static object testIEnum(object value) { if (!(value is AttributeCollection || value is ObjectIdCollection || value is SymbolTableRecord || value is IEnumerable<ObjectId>)) return value; return makeIEnum(value); } static IEnumerable<MyDynamicObject> makeIEnum(object value) { foreach (ObjectId oid in (IEnumerable)value) { yield return new MyDynamicObject(oid); } } public bool IsKindOf(Type type) { return DBObject.GetRXClass().IsDerivedFrom(RXClass.GetClass(type)); } } |