动态排序表达式问题

时间:2018-04-27 05:15:55

标签: sorting expression

假设我有像

这样的类层次结构
public class A
{
    public int AMember { get; set; }
}

public class B
{
    public int BMember { get; set; }
    public virtual A AasMember { get; set; }
}

public static class OrderByUtility
{
    public static bool PropertyExists<T>(string propertyName)
    {
        return typeof(T).GetProperty(propertyName, BindingFlags.IgnoreCase |
                     BindingFlags.Public) != null;
    }
}

每当我使用此实用程序时从主类

OrderByUtility.PropertyExists BClass>("BMember");

这样可以正常工作并返回TRUE。但每当我使用

OrderByUtility.PropertyExists BClass> ("AMember"); returns False

我希望所有Composed Object使用相同的PropertyExist函数。请建议解决此问题。感谢

1 个答案:

答案 0 :(得分:0)

这是一个非常天真的实现。您可以使其递归以继续检查嵌套类型。它还保留了一个缓存,因此它不会对每次查找进行昂贵的处理。

public class A
{
    public int AMember { get; set; }
}

public class B
{
    public int BMember { get; set; }
    public virtual A AasMember { get; set; }
}

public static class OrderByUtility
{
    private static readonly Dictionary<Type, Dictionary<string, bool>> Seen =
        new Dictionary<Type, Dictionary<string, bool>>();

    public static bool PropertyExists<T>(string propertyName)
    {
        var type = typeof(T);

        if (!Seen.TryGetValue(type, out var props))
        {
            props = new Dictionary<string, bool>();
            Seen[type] = props;
        }

        if (props.ContainsKey(propertyName))
        {
            return props[propertyName];
        }

        var prop = GetPropertyByName(type, propertyName);
        if (prop == null)
        {
            foreach (var p in type.GetProperties())
            {
                var propType = p.PropertyType;
                if (!propType.IsClass && !propType.IsInterface) continue;

                prop = GetPropertyByName(propType, propertyName);
                if (prop != null)
                {
                    break;
                }
            }
        }

        props[propertyName] = prop != null;
        return props[propertyName];
    }

    private static PropertyInfo GetPropertyByName(Type t, string name)
    {
        return t.GetProperty(name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    }
}

用法:

bool exists = OrderByUtility.PropertyExists<B>("AMember");