Skip to content

Instantly share code, notes, and snippets.

@BYJRK
Created November 14, 2023 13:07
Show Gist options
  • Save BYJRK/d751339b567ca41d72cfdde212be1e2e to your computer and use it in GitHub Desktop.
Save BYJRK/d751339b567ca41d72cfdde212be1e2e to your computer and use it in GitHub Desktop.
Ref Object.Property
var demo = new Demo();
demo.FieldValue = 10;
demo.PropValue = 10;
// 修改字段的值
ModifyFieldValue(ref demo.FieldValue, 42);
demo.FieldValue.Dump("Field Value");
// 修改属性的值
// ModifyFieldValue(ref demo.PropValue, 42);
ModifyPropValueWithDelegate(val => demo.PropValue = val, 42);
var method = typeof(Demo).GetProperty("PropValue")!.GetSetMethod()!;
//ModifyPropValueWithReflection(method, demo, 42);
ModifyPropValueWithExpression(d => d.PropValue, demo, 42);
demo.PropValue.Dump("Prop Value");
void ModifyFieldValue<T>(ref T field, T newValue)
{
field = newValue;
}
void ModifyPropValueWithDelegate<T>(Action<T> func, T newValue)
{
func.Invoke(newValue);
}
void ModifyPropValueWithReflection<TClass, TProp>(MethodInfo method, TClass target, TProp newValue)
{
method.Invoke(target, new object?[] { newValue });
}
void ModifyPropValueWithExpression<TClass, TProp>(Expression<Func<TClass, TProp>> expression, TClass target, TProp newValue)
{
var body = (MemberExpression)expression.Body;
var prop = (PropertyInfo)body.Member;
var setMethod = prop.GetSetMethod()!;
setMethod.Invoke(target, new object?[] { newValue });
}
class Demo
{
public int PropValue { get; set; }
public int FieldValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment