using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using System.Security.Cryptography; using System.Reflection; namespace ln.manage { public class ManagedNativeContainer : ManagedContainerBase where T:class,IDisposable { Type managedType; Dictionary propertyDescriptors = new Dictionary(); HashSet> managedNativeObjects = new HashSet>(); public ManagedNativeContainer(IManagedContainer parent) :this(parent, typeof(T).Name) { } public ManagedNativeContainer(IManagedContainer parent,String name) :base(parent,name) { managedType = typeof(T); foreach (FieldInfo fieldInfo in managedType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (fieldInfo.IsPublic || fieldInfo.GetCustomAttribute() != null) { NativePropertyDescriptor nativePropertyDescriptor = new NativePropertyDescriptor(this, fieldInfo); propertyDescriptors.Add(nativePropertyDescriptor.PropertyName,nativePropertyDescriptor); } } foreach (PropertyInfo propertyInfo in managedType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { if (propertyInfo.GetGetMethod().IsPublic || propertyInfo.GetCustomAttribute() != null) { NativePropertyDescriptor nativePropertyDescriptor = new NativePropertyDescriptor(this, propertyInfo); propertyDescriptors.Add(nativePropertyDescriptor.PropertyName, nativePropertyDescriptor); } } foreach (NativePropertyDescriptor nativePropertyDescriptor in NativePropertyDescriptors) { if (nativePropertyDescriptor.Identity) IdentityDescriptor = nativePropertyDescriptor; } } public IEnumerable NativePropertyDescriptors => propertyDescriptors.Values; public NativePropertyDescriptor GetNativePropertyDescriptor(string propertyName) => propertyDescriptors[propertyName]; public NativePropertyDescriptor IdentityDescriptor { get; } public override IEnumerable PropertyDescriptors => propertyDescriptors.Values; public override string IdentityPropertyName => IdentityDescriptor.PropertyName; public override IManagedObject CreateManagedObject() { ManagedNativeObject managedNativeObject = new ManagedNativeObject(this); managedNativeObjects.Add(managedNativeObject); return managedNativeObject; } public override bool DisposeManagedObject(object identity) => DisposeManagedObject(GetManagedObject(identity)); public bool DisposeManagedObject(ManagedNativeObject managedNativeObject) { if (managedNativeObjects.Contains(managedNativeObject)) { managedNativeObject.Enabled = false; managedNativeObjects.Remove(managedNativeObject); return true; } return false; } public override IManagedObject GetManagedObject(object identity) { foreach (ManagedNativeObject managedNativeObject in managedNativeObjects) { if (Object.Equals(managedNativeObject.Identity, identity)) return managedNativeObject; } throw new KeyNotFoundException(); } public override IManagedObject[] GetManagedObjects() { return managedNativeObjects.Cast().ToArray(); } } }