diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs new file mode 100644 index 00000000..46468367 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -0,0 +1,58 @@ +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; + } + + /// + /// 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); + } +}