record Person { public int Age; public int Height { get; set; } }
一、声明一个Person类,它有一个字段Age和一个属性Height.
二、针对字段,我们可以通过ref传递引用
代码如下
static void ModifyValue<T>(ref T field, T value) { field = value; } var person = new Person(); person.Age = 1; person.Height = 100; Console.WriteLine(person); ModifyValue<int>(ref person.Age, 10); Console.WriteLine(person);
查看输出:
三、针对属性,我们尝试使用ref传递
发现报错。
四、那么如何传递一个属性的引用呢?
方式一:通过委托
static void ModifyValueByDelegate1<T>(Action< T> action, T value) { action.Invoke( value); } var person = new Person(); person.Age = 1; person.Height = 100; Console.WriteLine(person); ModifyValueByDelegate1<int>(x => person.Height = x, 100111); Console.WriteLine(person);
方式二:通过反射,我们知道属性其实是一个get方法和一个set方法。
static void ModifyValueByReflection<T,TClass>(MethodInfo method,TClass @class, T value) { method.Invoke(@class,new object?[]{value}); } var person = new Person(); person.Age = 1; person.Height = 100; Console.WriteLine(person); ModifyValueByReflection<int, Person>(typeof(Person).GetProperty(nameof(person.Height)).GetSetMethod(),person,999); Console.WriteLine(person);
方式三:借助表达式树
static void ModifyValueByExpression<T,TClass>(Expression<Func<TClass,T>> expression,TClass @class,T value) { var body = (MemberExpression)expression.Body ; var prop =(PropertyInfo) body.Member; var setMethod = prop.GetSetMethod(); setMethod.Invoke(@class, new object?[] { value }); } var person = new Person(); person.Age = 1; person.Height = 100; Console.WriteLine(person); ModifyValueByExpression(d => d.Height, person, 888); Console.WriteLine(person);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下