|
|
|
@ -9,8 +9,7 @@ namespace Volo.Abp; |
|
|
|
|
|
|
|
public static class ObjectHelper |
|
|
|
{ |
|
|
|
private static readonly ConcurrentDictionary<string, PropertyInfo?> CachedObjectProperties = |
|
|
|
new ConcurrentDictionary<string, PropertyInfo?>(); |
|
|
|
private static readonly ConcurrentDictionary<string, PropertyInfo?> _cachedObjectProperties = new(); |
|
|
|
|
|
|
|
public static void TrySetProperty<TObject, TValue>( |
|
|
|
TObject obj, |
|
|
|
@ -27,37 +26,53 @@ public static class ObjectHelper |
|
|
|
Func<TObject, TValue> valueFactory, |
|
|
|
params Type[]? ignoreAttributeTypes) |
|
|
|
{ |
|
|
|
var cacheKey = $"{obj?.GetType().FullName}-" + |
|
|
|
$"{propertySelector}-" + |
|
|
|
$"{(ignoreAttributeTypes != null ? "-" + string.Join("-", ignoreAttributeTypes.Select(x => x.FullName)) : "")}"; |
|
|
|
var cacheKey = |
|
|
|
$"{obj?.GetType().FullName}-{propertySelector}-{(ignoreAttributeTypes != null ? "-" + string.Join("-", ignoreAttributeTypes.Select(x => x.FullName)) : "")}"; |
|
|
|
|
|
|
|
var property = CachedObjectProperties.GetOrAdd(cacheKey, () => |
|
|
|
var property = _cachedObjectProperties.GetOrAdd(cacheKey, PropertyFactory); |
|
|
|
|
|
|
|
property?.SetValue(obj, valueFactory(obj)); |
|
|
|
return; |
|
|
|
|
|
|
|
PropertyInfo? PropertyFactory(string _) |
|
|
|
{ |
|
|
|
if (propertySelector.Body.NodeType != ExpressionType.MemberAccess) |
|
|
|
MemberExpression? memberExpression; |
|
|
|
switch (propertySelector.Body.NodeType) |
|
|
|
{ |
|
|
|
case ExpressionType.Convert: { |
|
|
|
memberExpression = propertySelector.Body.As<UnaryExpression>().Operand as MemberExpression; |
|
|
|
break; |
|
|
|
} |
|
|
|
case ExpressionType.MemberAccess: { |
|
|
|
memberExpression = propertySelector.Body.As<MemberExpression>(); |
|
|
|
break; |
|
|
|
} |
|
|
|
default: { |
|
|
|
return null; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if (memberExpression == null) |
|
|
|
{ |
|
|
|
return null; |
|
|
|
} |
|
|
|
|
|
|
|
var memberExpression = propertySelector.Body.As<MemberExpression>(); |
|
|
|
|
|
|
|
var propertyInfo = obj?.GetType().GetProperties().FirstOrDefault(x => |
|
|
|
x.Name == memberExpression.Member.Name && |
|
|
|
x.GetSetMethod(true) != null); |
|
|
|
var propertyInfo = obj?.GetType() |
|
|
|
.GetProperties() |
|
|
|
.FirstOrDefault(x => x.Name == memberExpression.Member.Name && x.GetSetMethod(true) != null); |
|
|
|
|
|
|
|
if (propertyInfo == null) |
|
|
|
{ |
|
|
|
return null; |
|
|
|
} |
|
|
|
|
|
|
|
if (ignoreAttributeTypes != null && |
|
|
|
ignoreAttributeTypes.Any(ignoreAttribute => propertyInfo.IsDefined(ignoreAttribute, true))) |
|
|
|
if (ignoreAttributeTypes != null && ignoreAttributeTypes.Any(ignoreAttribute => propertyInfo.IsDefined(ignoreAttribute, true))) |
|
|
|
{ |
|
|
|
return null; |
|
|
|
} |
|
|
|
|
|
|
|
return propertyInfo; |
|
|
|
}); |
|
|
|
|
|
|
|
property?.SetValue(obj, valueFactory(obj)); |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
|