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

2023-12-13 03:28:41
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;
        }
    }
}

在这里插入图片描述

文章来源:https://blog.csdn.net/helldoger/article/details/134896629
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。