using System; using System.Linq.Expressions; using System.Reflection; namespace DynamicDescriptors; /// /// Provides various reflection-related methods. /// internal static class Reflect { /// /// Returns the name of the property referred to by the specified property expression. /// /// /// Type containing the property. /// /// /// Type of the property. /// /// /// An representing a Func mapping an instance of type TSource /// to an instance of type TProperty. /// /// /// The name of the property referred to by the specified property expression. /// public static string GetPropertyName(Expression> propertyExpression) { if (propertyExpression == null) { throw new ArgumentNullException(nameof(propertyExpression)); } return GetPropertyInfo(propertyExpression).Name; } /// /// Returns a instance for the property referred to by the specified /// property expression. /// /// /// Type containing the property. /// /// /// Type of the property. /// /// /// An representing a Func mapping an instance of type TSource to an instance /// of type TProperty. /// /// /// A instance for the property referred to by the specified /// property expression. /// public static PropertyInfo GetPropertyInfo(Expression> propertyExpression) { if (propertyExpression == null) { throw new ArgumentNullException(nameof(propertyExpression)); } var member = propertyExpression.Body as MemberExpression; if (member == null) { throw new ArgumentException($"Expression '{propertyExpression}' refers to a method, not a property."); } var propertyInfo = member.Member as PropertyInfo; if (propertyInfo == null) { throw new ArgumentException($"Expression '{propertyExpression}' refers to a field, not a property."); } return propertyInfo; } }