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);
标签:Console,C#,value,Height,person,引用,WriteLine,var,属性 From: https://www.cnblogs.com/lixiang1998/p/17852297.html