You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态排序表达式问题:C#属性存在判断工具类如何支持嵌套属性?

解决嵌套属性路径的存在性验证问题

你的问题核心是现有PropertyExists<T>方法只能处理单层属性名称,无法识别带.的嵌套属性路径。我们可以通过拆分属性路径、逐层验证每个层级的属性来解决这个问题。

修改后的OrderByUtility实现

using System;
using System.Reflection;

public static class OrderByUtility
{
    public static bool PropertyExists<T>(string propertyPath)
    {
        // 处理空路径或空白字符串的情况
        if (string.IsNullOrWhiteSpace(propertyPath))
            return false;

        Type currentType = typeof(T);
        // 按"."拆分属性路径
        string[] propertyNames = propertyPath.Split('.');

        foreach (string propertyName in propertyNames)
        {
            // 检查当前类型是否包含指定属性
            PropertyInfo property = currentType.GetProperty(
                propertyName, 
                BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance
            );

            if (property == null)
                return false;

            // 切换到下一层级的类型,继续验证
            currentType = property.PropertyType;
        }

        // 所有层级的属性都存在
        return true;
    }
}

关键逻辑说明

  • 路径拆分:用Split('.')把嵌套路径拆分为单个属性名称,比如"AasMember.AMember"会拆成["AasMember", "AMember"]。
  • 逐层验证:从根类型T开始,依次检查每个属性是否存在;如果某一层找不到属性,直接返回false。
  • 类型切换:每找到一个属性后,将当前类型切换为该属性的类型,继续验证下一层级的属性。
  • 边界处理:增加了对空路径/空白字符串的判断,避免异常。

测试示例

// 验证单层属性,返回true
bool hasBMember = OrderByUtility.PropertyExists<B>("BMember");

// 验证嵌套属性,返回true
bool hasNestedMember = OrderByUtility.PropertyExists<B>("AasMember.AMember");

// 验证不存在的嵌套属性,返回false
bool hasInvalidNested = OrderByUtility.PropertyExists<B>("AasMember.InvalidProperty");

这样修改后,你的动态排序场景中就能正确识别嵌套属性路径了。

内容的提问来源于stack exchange,提问作者Zeeshan Maqsood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:43