C#中如何借助委托|反射|表达式来传递类对象属性的“引用”

本文介绍了如何在C#中使用LINQ表达式树、反射和闭包技术来动态修改类的属性和字段值,包括直接赋值、通过反射调用setter方法和使用lambda表达式设置属性。
using System.Linq.Expressions;
using System.Reflection;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Demon demon = new() { MyField = 1, MyProperty = 2, };

            //修改字段
            void Modify<T>(ref T field, T newValue)
            {
                field = newValue;
            }
            //通过 传入Action 闭包修改属性
            void ModifyProperty<T>(Action<T> action, T newValue)
            {
                action.Invoke(newValue);
            }

            //通过 反射修改属性
            void ModifyPropertyByRelection<TClass, TProperty>(MethodInfo methodInfo, TClass target,TProperty newValue)
            {
                methodInfo.Invoke(target, new object?[] { newValue });
            }

            //通过 表达式树修改属性
            void ModifyPropertyWithExpression<TProperty, TClass>(Expression<Func<Demon, TProperty>> expression, TClass target, TProperty newValue)
            {
                var body = (MemberExpression)expression.Body;
                var prop = body.Member as PropertyInfo;
                var setMethod = prop!.GetSetMethod();
                setMethod?.Invoke(target, new object?[] { newValue });
            }

            ModifyPropertyWithExpression(d => d.MyProperty, demon, 42);
            Console.WriteLine(demon.MyProperty);


            var method = typeof(Demon).GetProperty(nameof(demon.MyProperty))!.GetSetMethod()!;

            ModifyPropertyByRelection(method, demon,88);

            Console.WriteLine(demon.MyProperty);

            Modify(ref demon.MyField, 55);
            Console.WriteLine(demon.MyField);

            ModifyProperty(x=> demon.MyProperty = x, 66);
            Console.WriteLine(demon.MyProperty);
            
        }



        class Demon
        {
            public int MyProperty { get; set; }
            public int MyField;
        }
    }
}

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值