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

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;
        }
    }
}

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

你可能感兴趣的:(c#,开发语言)