|
1 | | -// Licensed to the .NET Foundation under one or more agreements. |
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
2 | 2 | // The .NET Foundation licenses this file to you under the Apache 2.0 License |
3 | 3 | // See the LICENSE file in the project root for more information. |
4 | 4 | // Maintainer: Argo Zhang(argo@live.ca) Website: https://www.blazor.zone |
@@ -662,24 +662,27 @@ Expression<Func<TModel, TResult>> GetSimplePropertyExpression() |
662 | 662 | Expression<Func<TModel, TResult>> GetComplexPropertyExpression() |
663 | 663 | { |
664 | 664 | var propertyNames = propertyName.Split("."); |
665 | | - Expression? body = null; |
666 | | - Type t = type; |
667 | | - object? propertyInstance = model; |
| 665 | + Expression body = Expression.Convert(parameter, type); |
668 | 666 | foreach (var name in propertyNames) |
669 | 667 | { |
670 | | - var p = t.GetPropertyByName(name) ?? throw new InvalidOperationException($"类型 {type.Name} 未找到 {name} 属性,无法获取其值"); |
671 | | - propertyInstance = p.GetValue(propertyInstance); |
672 | | - if (propertyInstance != null) |
673 | | - { |
674 | | - t = propertyInstance.GetType(); |
675 | | - } |
676 | | - |
677 | | - body = Expression.Property(body ?? Expression.Convert(parameter, type), p); |
| 668 | + body = BuildPropertyAccess(body, body.Type, name); |
678 | 669 | } |
679 | | - return Expression.Lambda<Func<TModel, TResult>>(Expression.Convert(body!, typeof(TResult)), parameter); |
| 670 | + return Expression.Lambda<Func<TModel, TResult>>(Expression.Convert(body, typeof(TResult)), parameter); |
680 | 671 | } |
681 | 672 | } |
682 | 673 |
|
| 674 | + private static ConditionalExpression BuildPropertyAccess(Expression instance, Type instanceType, string propertyName) |
| 675 | + { |
| 676 | + var p = instanceType.GetPropertyByName(propertyName) ?? throw new InvalidOperationException($"类型 {instanceType.Name} 未找到 {propertyName} 属性,无法获取其值"); |
| 677 | + |
| 678 | + var propertyAccess = Expression.Property(instance, p); |
| 679 | + return Expression.Condition( |
| 680 | + test: Expression.Equal(instance, Expression.Constant(null, instanceType)), |
| 681 | + ifTrue: Expression.Constant(null, p.PropertyType), |
| 682 | + ifFalse: propertyAccess |
| 683 | + ); |
| 684 | + } |
| 685 | + |
683 | 686 | /// <summary> |
684 | 687 | /// 给指定模型属性赋值 Lambda 表达式 |
685 | 688 | /// </summary> |
|
0 commit comments