如何使用表达式访问属于类的属性

时间:2018-01-19 15:18:02

标签: c# expression-trees

我有一个名为“User”的类,它有一个属性定义为“Department”类(我也想知道它叫什么,LOL)。我想访问名为“Name”(User.Department.Name)的“Department”类中的属性。当我将争论输入到已编译的表达式中时,它会抛出NulLReferenceException。

我在下面有这个代码。提前谢谢。

        ParameterExpression paramExpr = Expression.Parameter(typeof(User), "user");
        MemberExpression depPropExpr = MemberExpression.Property(paramExpr, "Department");
        MemberExpression depNamePropExpr = MemberExpression.Property(depPropExpr, "Name");
        ConstantExpression constantExpression = Expression.Constant("SBCA");

        var expression = Expression.Assign(depNamePropExpr, constantExpression); var compiledExpression = Expression.Lambda<Action<User>>(expression, new[] { paramExpr }).Compile();
        compiledExpression(user);

1 个答案:

答案 0 :(得分:0)

正如您在此.NET Fiddle中看到的,您的代码运行正常。

public class Program
{

    public static void Main()
    {
        var user = new User();
        user.Department = new Department();
        user.Department.Name = "hello";
        Console.WriteLine("Before: " + user.Department.Name);

        ParameterExpression paramExpr = Expression.Parameter(typeof(User), "user");
        MemberExpression depPropExpr = MemberExpression.Property(paramExpr, "Department");
        MemberExpression depNamePropExpr = MemberExpression.Property(depPropExpr, "Name");
        ConstantExpression constantExpression = Expression.Constant("SBCA");

        var expression = Expression.Assign(depNamePropExpr, constantExpression);

        var compiledExpression = Expression.Lambda<Action<User>>(expression, new[] { paramExpr }).Compile();
        compiledExpression(user);
        Console.WriteLine("After: " + user.Department.Name);
    }
}

public class User
{
    public Department Department { get; set; }
}

public class Department
{
    public string Name { get; set; }    
}

输出:

  

之前:你好   之后:SBCA

问题(NullReferenceException)是user.Departmentnull,您的表达式正在user.Department.Name = "SBCA";。 您可以通过删除user.Department = new...

的分配来对此进行测试