#nullable disable
using System;
using System.Reflection;
namespace StardewModdingAPI.Framework.Reflection
{
/// A property obtained through reflection.
/// The property value type.
internal class ReflectedProperty : IReflectedProperty
{
/*********
** Fields
*********/
/// The display name shown in error messages.
private readonly string DisplayName;
/// The underlying property getter.
private readonly Func GetMethod;
/// The underlying property setter.
private readonly Action SetMethod;
/*********
** Accessors
*********/
///
public PropertyInfo PropertyInfo { get; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The type that has the property.
/// The object that has the instance property (if applicable).
/// The reflection metadata.
/// Whether the property is static.
/// The or is null.
/// The is null for a non-static property, or not null for a static property.
public ReflectedProperty(Type parentType, object obj, PropertyInfo property, bool isStatic)
{
// validate input
if (parentType == null)
throw new ArgumentNullException(nameof(parentType));
if (property == null)
throw new ArgumentNullException(nameof(property));
// validate static
if (isStatic && obj != null)
throw new ArgumentException("A static property cannot have an object instance.");
if (!isStatic && obj == null)
throw new ArgumentException("A non-static property must have an object instance.");
this.DisplayName = $"{parentType.FullName}::{property.Name}";
this.PropertyInfo = property;
if (this.PropertyInfo.GetMethod != null)
this.GetMethod = (Func)Delegate.CreateDelegate(typeof(Func), obj, this.PropertyInfo.GetMethod);
if (this.PropertyInfo.SetMethod != null)
this.SetMethod = (Action)Delegate.CreateDelegate(typeof(Action), obj, this.PropertyInfo.SetMethod);
}
///
public TValue GetValue()
{
if (this.GetMethod == null)
throw new InvalidOperationException($"The {this.DisplayName} property has no get method.");
try
{
return this.GetMethod();
}
catch (InvalidCastException)
{
throw new InvalidCastException($"Can't convert the {this.DisplayName} property from {this.PropertyInfo.PropertyType.FullName} to {typeof(TValue).FullName}.");
}
catch (Exception ex)
{
throw new Exception($"Couldn't get the value of the {this.DisplayName} property", ex);
}
}
///
public void SetValue(TValue value)
{
if (this.SetMethod == null)
throw new InvalidOperationException($"The {this.DisplayName} property has no set method.");
try
{
this.SetMethod(value);
}
catch (InvalidCastException)
{
throw new InvalidCastException($"Can't assign the {this.DisplayName} property a {typeof(TValue).FullName} value, must be compatible with {this.PropertyInfo.PropertyType.FullName}.");
}
catch (Exception ex)
{
throw new Exception($"Couldn't set the value of the {this.DisplayName} property", ex);
}
}
}
}