You need to enable JavaScript to run this app. 如何为C# record的with运算符构造表达式树以实现嵌套Lens功能
优惠活动
大模型
产品
解决方案
定价
更多

如何为C# record的with运算符构造表达式树以实现嵌套Lens功能

为嵌套record的with运算符构造表达式树实现方案

C#中record的with运算符编译后会触发编译器生成的<Clone>$方法调用,生成原对象的浅拷贝后对指定init属性赋值,嵌套场景只需要拆解属性访问链,递归生成每层的克隆赋值逻辑即可。


实现步骤

1. 拆解属性访问链

从输入的选择器表达式中提取从根参数到目标属性的所有属性信息,例如manager => manager.Employee.Name拆解后得到属性列表:[typeof(Manager).GetProperty("Employee"), typeof(Employee).GetProperty("Name")]

2. 递归生成嵌套克隆赋值逻辑

从最内层属性开始,逐层向外构造with对应的表达式:

  • 最内层:为Employee类型实例的Name属性赋值新值
  • 外层:为Manager类型实例的Employee属性赋值为内层生成的修改后的Employee实例

完整代码实现

using System.Linq.Expressions;
using System.Reflection;

public static class LensGenerator
{
    public static Func<T, TValue, T> CreateUpdateFunc<T, TValue>(Expression<Func<T, TValue>> selector)
    {
        // 拆解属性访问链
        var propChain = GetPropertyChain(selector.Body).Reverse().ToList();
        if (propChain.Count == 0)
            throw new ArgumentException("无效的属性选择器");
        
        // 定义两个输入参数:原对象、新属性值
        var sourceParam = Expression.Parameter(typeof(T), "source");
        var newValueParam = Expression.Parameter(typeof(TValue), "newValue");

        // 从最内层开始构造嵌套的with逻辑
        Expression currentExpr = newValueParam;
        for (int i = propChain.Count - 1; i >= 0; i--)
        {
            var currentProp = propChain[i];
            var declaringType = currentProp.DeclaringType!;
            // 获取当前类型的<Clone>$方法(编译器为record生成的克隆方法)
            var cloneMethod = declaringType.GetMethod("<Clone>$", BindingFlags.Public | BindingFlags.Instance)!;
            
            // 生成当前层级的原对象访问表达式
            Expression sourceAccess = sourceParam;
            for (int j = 0; j < i; j++)
            {
                sourceAccess = Expression.Property(sourceAccess, propChain[j]);
            }
            
            // 调用克隆方法生成副本
            var cloneExpr = Expression.Call(sourceAccess, cloneMethod);
            // 给副本的当前属性赋值
            var memberAssign = Expression.Bind(currentProp, currentExpr);
            var memberInit = Expression.MemberInit(cloneExpr, memberAssign);
            
            currentExpr = memberInit;
        }

        // 编译为委托
        return Expression.Lambda<Func<T, TValue, T>>(currentExpr, sourceParam, newValueParam).Compile();
    }

    // 递归提取属性访问链
    private static IEnumerable<PropertyInfo> GetPropertyChain(Expression expression)
    {
        while (expression is MemberExpression memberExpr && memberExpr.Member is PropertyInfo prop)
        {
            yield return prop;
            expression = memberExpr.Expression!;
        }
        if (expression is not ParameterExpression)
            throw new ArgumentException("选择器必须是属性访问链");
    }
}

测试用例

// 定义测试用record
record Employee(string Name, int Age);
record Manager(string Name, Employee Employee);

// 测试代码
public static void Main()
{
    // 生成嵌套属性的更新函数
    var updateManagerEmployeeName = LensGenerator.CreateUpdateFunc<Manager, string>(m => m.Employee.Name);
    
    // 构造测试数据
    var originalManager = new Manager("张经理", new Employee("小李", 25));
    
    // 调用更新函数
    var updatedManager = updateManagerEmployeeName(originalManager, "小王");
    
    // 验证结果
    Console.WriteLine(originalManager.Employee.Name); // 输出:小李
    Console.WriteLine(updatedManager.Employee.Name); // 输出:小王
    Console.WriteLine(ReferenceEquals(originalManager, updatedManager)); // 输出:False(根对象已克隆)
    Console.WriteLine(ReferenceEquals(originalManager.Employee, updatedManager.Employee)); // 输出:False(嵌套对象也已克隆)
}

补充说明

  • 该实现兼容任意层级的嵌套属性,比如a => a.Prop1.Prop2.Prop3的场景也可以自动生成三层嵌套的with表达式
  • 仅支持record类型,因为依赖编译器生成的<Clone>$方法,如果需要支持class类型可以自行修改克隆逻辑为手动拷贝所有属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:15:03