using System; using System.Diagnostics.Contracts; using System.Reflection; namespace ComputeSharp.Shaders.Translation.Models { /// /// A that wraps a readable member of another and provides access to it /// internal sealed class ReadableMember { /// /// The object wrapped by the current instance, if present /// private readonly FieldInfo? Field; /// /// The object wrapped by the current instance, if present /// private readonly PropertyInfo? Property; /// /// Creates a new instance with the given parameters /// /// The optional object wrapped by the current instance /// The optional object wrapped by the current instance private ReadableMember(FieldInfo? field, PropertyInfo? property) { Field = field; Property = property; } /// /// Gets the of the wrapped member for the current instance /// public Type MemberType { get { if (Field != null) return Field.FieldType; if (Property != null) return Property.PropertyType; throw new InvalidOperationException("Field and property can't both be null at the same time"); } } /// /// Gets the name of the wrapped member for the current instance /// public string Name => (Field?.Name ?? Property?.Name) ?? throw new InvalidOperationException("Field and property can't both be null at the same time"); /// /// Returns the value of the wrapped member for the current instance /// /// The target instance to use to read the value from [Pure] public object GetValue(object? instance) { if (Field != null) return Field.GetValue(instance); if (Property != null) return Property.GetValue(instance); throw new InvalidOperationException("Field and property can't both be null at the same time"); } /// /// Converts a object into a instance /// /// The input object to wrap public static implicit operator ReadableMember(FieldInfo field) => new ReadableMember(field, null); /// /// Converts a object into a instance /// /// The input object to wrap public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(null, property); } }