使用 .NET 4.5.2 时找不到 GetMemberInfo

GetMemberInfo not found when using .NET 4.5.2

我在使用 Framework .NET 4.5 的库项目中使用此代码,它工作正常

protected void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
{
    if (this.IsInpcActive)
    {
        this.OnPropertyChanged(property.GetMemberInfo().Name);
    }
}

我将此代码复制粘贴到使用 .NET Framework 4.5.2 的项目中,但收到此错误消息:

'System.Linq.Expressions.Expression<System.Func<TProperty>>' does not contain a definition for 'GetMemberInfo' and no extension method 'GetMemberInfo' accepting a first argument of type 'System.Linq.Expressions.Expression<System.Func<TProperty>>' could be found (are you missing a using directive or an assembly reference?

实在不想浪费太多时间,所以找到了B计划:扩展方法:

internal static class ExpressionExtensions
{
    #region Methods

    public static MemberInfo GetMemberInfo(this Expression expression)
    {
        var lambda = (LambdaExpression)expression;

        MemberExpression memberExpression;
        if (lambda.Body is UnaryExpression)
        {
            var unaryExpression = (UnaryExpression)lambda.Body;
            memberExpression = (MemberExpression)unaryExpression.Operand;
        }
        else
            memberExpression = (MemberExpression)lambda.Body;

        return memberExpression.Member;
    }

    #endregion Methods
}

但我很好奇:这个方法去哪儿了?

Expression<TDelegate> class 没有方法 GetMemberInfo(),而且从来没有。所以你的问题似乎出在这里:

I copy-pasted this code in a project

所以在我看来,您针对 4.5 编译的版本使用了相同或等效的扩展方法,否则它不会编译。

参见示例 this one from the Enterprise Library:

StaticReflection.GetMemberInfo<T, TProperty> Method

Retrieves a PropertyInfo object for the set method from an expression in the form x => x.SomeProperty.

所以你的原始代码应该在顶部有这个:

using Microsoft.Practices.EnterpriseLibrary.Common.Utility;

以及对企业库的引用。