RaspberryIO_26/Swan.Lite/Reflection/PropertyProxy.cs

44 lines
1.7 KiB
C#
Raw Permalink Normal View History

2019-12-04 18:57:18 +01:00
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
2019-12-08 19:54:52 +01:00
namespace Swan.Reflection {
/// <summary>
/// Represents a generic class to store getters and setters.
/// </summary>
/// <typeparam name="TClass">The type of the class.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <seealso cref="IPropertyProxy" />
public sealed class PropertyProxy<TClass, TProperty> : IPropertyProxy where TClass : class {
private readonly Func<TClass, TProperty> _getter;
private readonly Action<TClass, TProperty> _setter;
2019-12-04 18:57:18 +01:00
/// <summary>
2019-12-08 19:54:52 +01:00
/// Initializes a new instance of the <see cref="PropertyProxy{TClass, TProperty}"/> class.
2019-12-04 18:57:18 +01:00
/// </summary>
2019-12-08 19:54:52 +01:00
/// <param name="property">The property.</param>
public PropertyProxy(PropertyInfo property) {
if(property == null) {
throw new ArgumentNullException(nameof(property));
}
MethodInfo getterInfo = property.GetGetMethod(false);
if(getterInfo != null) {
this._getter = (Func<TClass, TProperty>)Delegate.CreateDelegate(typeof(Func<TClass, TProperty>), getterInfo);
}
MethodInfo setterInfo = property.GetSetMethod(false);
if(setterInfo != null) {
this._setter = (Action<TClass, TProperty>)Delegate.CreateDelegate(typeof(Action<TClass, TProperty>), setterInfo);
}
}
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
Object IPropertyProxy.GetValue(Object instance) => this._getter(instance as TClass);
/// <inheritdoc />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IPropertyProxy.SetValue(Object instance, Object value) => this._setter(instance as TClass, (TProperty)value);
}
2019-12-04 18:57:18 +01:00
}