以安全的方式将 PropertyInfo 名称与现有 属性 进行比较

Compare PropertyInfo name to an existing property in a safe way

我有一个 PropertyInfo,我想检查它是否是特定的。知道它的 ReflectedType 是正确的,我可以这样做:

bool TestProperty(PropertyInfo prop)
{
    return prop.Name == "myPropertyName";
}

问题是我的 属性 myPropertyName 将来可能会更改名称,我无法意识到上面的代码刚刚崩溃了。

有没有一种安全的方法来测试我想要的东西,可能是使用表达式?

如果您可以为 属性 创建 Expression,则可以从此表达式中检索名称:

public static string PropertyName<T>(this Expression<Func<T, object>> propertyExpression)
{
    MemberExpression mbody = propertyExpression.Body as MemberExpression;

    if (mbody == null)
    {
        //This will handle Nullable<T> properties.
        UnaryExpression ubody = propertyExpression.Body as UnaryExpression;

        if (ubody != null)
        {
            mbody = ubody.Operand as MemberExpression;
        }

        if (mbody == null)
        {
            throw new ArgumentException("Expression is not a MemberExpression", "propertyExpression");
        }
    }

    return mbody.Member.Name;
}

接下来就可以使用了:

bool TestProperty(PropertyInfo prop)
{
    return prop.Name == Extensions.PropertyName<TargetClass>(x => x.myPropertyName);;
}