ant-design-blazor/components/core/Reflection/PropertyReflector.cs
anranruye c06e73ba5b feat(module: table): add support for Display attribute (#1310)
feat(module:table): add support for Display attribute

Display attribute is widely used to specify display text for entity properties.
Table component should get column names from Display attribute instances.

Closes #1278
2021-04-04 20:38:57 +08:00

57 lines
2.0 KiB
C#

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; }
public RequiredAttribute RequiredAttribute { get; set; }
public string DisplayName { get; set; }
public string PropertyName { get; set; }
private PropertyReflector(PropertyInfo propertyInfo)
{
this.PropertyInfo = propertyInfo;
this.RequiredAttribute = propertyInfo.GetCustomAttribute<RequiredAttribute>(true);
this.DisplayName = propertyInfo.GetCustomAttribute<DisplayNameAttribute>(true)?.DisplayName ??
propertyInfo.GetCustomAttribute<DisplayAttribute>(true)?.Name ??
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);
}
}
}