2020-09-01 17:23:31 +08:00
using System ;
using System.Collections.Generic ;
using System.ComponentModel ;
using System.ComponentModel.DataAnnotations ;
using System.Linq.Expressions ;
using System.Reflection ;
namespace AntDesign.Core.Reflection
{
internal struct PropertyReflector
{
public PropertyInfo PropertyInfo { get ; }
2020-10-25 19:03:58 +08:00
public RequiredAttribute RequiredAttribute { get ; set ; }
2020-09-01 17:23:31 +08:00
public string DisplayName { get ; set ; }
public string PropertyName { get ; set ; }
private PropertyReflector ( PropertyInfo propertyInfo )
{
this . PropertyInfo = propertyInfo ;
2020-10-25 19:03:58 +08:00
this . RequiredAttribute = propertyInfo . GetCustomAttribute < RequiredAttribute > ( true ) ;
2020-09-01 17:23:31 +08:00
this . DisplayName = propertyInfo . GetCustomAttribute < DisplayNameAttribute > ( true ) ? . DisplayName ? ? propertyInfo . Name ;
this . PropertyName = PropertyInfo . Name ;
}
public static PropertyReflector Create < TField > ( Expression < Func < TField > > accessor )
{
if ( accessor = = null )
{
throw new ArgumentNullException ( nameof ( accessor ) ) ;
}
var accessorBody = accessor . Body ;
if ( accessorBody is UnaryExpression unaryExpression
& & unaryExpression . NodeType = = ExpressionType . Convert
& & unaryExpression . Type = = typeof ( object ) )
{
accessorBody = unaryExpression . Operand ;
}
if ( ! ( accessorBody is MemberExpression memberExpression ) )
{
throw new ArgumentException ( $"The provided expression contains a {accessorBody.GetType().Name} which is not supported. {nameof(PropertyReflector)} only supports simple member accessors (fields, properties) of an object." ) ;
}
var property = memberExpression . Member as PropertyInfo ;
return new PropertyReflector ( property ) ;
}
}
}