<PackageReference Include="Castle.Core" Version="3.3.3" />

RemoveIfAttribute

Removes a property if matches value.
using System; using System.Collections; using System.Linq; using System.Reflection; namespace Castle.Components.DictionaryAdapter { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = true)] public class RemoveIfAttribute : DictionaryBehaviorAttribute, IDictionaryPropertySetter, IDictionaryBehavior { private class ValueCondition : ICondition { private readonly object[] values; private readonly IEqualityComparer comparer; public ValueCondition(object[] values, IEqualityComparer comparer) { this.values = values; this.comparer = comparer; } public bool SatisfiedBy(object value) { return values.Any(delegate(object valueToMatch) { if (comparer == null) return object.Equals(value, valueToMatch); return comparer.Equals(value, valueToMatch); }); } } private ICondition condition; public Type Condition { set { condition = Construct<ICondition>(value, "value"); } } public RemoveIfAttribute() { base.ExecutionOrder += 10; } public RemoveIfAttribute(params object[] values) : this() { object array = values; if (array == null) { object[] array2 = new object[1]; array = array2; } values = (object[])array; condition = new ValueCondition(values, null); } public RemoveIfAttribute(object[] values, Type comparerType) : this() { IEqualityComparer comparer = Construct<IEqualityComparer>(comparerType, "comparerType"); condition = new ValueCondition(values, comparer); } protected RemoveIfAttribute(ICondition condition) : this() { this.condition = condition; } bool IDictionaryPropertySetter.SetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, ref object value, PropertyDescriptor property) { if (ShouldRemove(value)) { dictionaryAdapter.ClearProperty(property, key); return false; } return true; } internal bool ShouldRemove(object value) { if (condition != null) return condition.SatisfiedBy(value); return false; } private static TBase Construct<TBase>(Type type, string paramName) where TBase : class { if ((object)type == null) throw new ArgumentNullException(paramName); if (!type.IsAbstract && typeof(TBase).IsAssignableFrom(type)) { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if ((object)constructor != null) return (TBase)constructor.Invoke(new object[0]); } throw new ArgumentException($"{type.FullName}""{typeof(TBase).FullName}"""); } } }