在C#中,可以通过变量名获取和设置属性。以下是一些常用的方法:
using System.Reflection;
public static object GetPropertyValue(object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
public static void SetPropertyValue(object obj, string propertyName, object value)
{
obj.GetType().GetProperty(propertyName).SetValue(obj, value, null);
}
using System.Dynamic;
public static object GetPropertyValue(object obj, string propertyName)
{
dynamic dynObj = obj;
return dynObj.GetType().GetProperty(propertyName).GetValue(obj, null);
}
public static void SetPropertyValue(object obj, string propertyName, object value)
{
dynamic dynObj = obj;
dynObj.GetType().GetProperty(propertyName).SetValue(obj, value, null);
}
using System.Linq.Expressions;
public static object GetPropertyValue(object obj, string propertyName)
{
var param = Expression.Parameter(obj.GetType(), "x");
var property = Expression.Property(param, propertyName);
var lambda = Expression.Lambda(property, param);
var getter = (Func<object, object>)lambda.Compile();
return getter(obj);
}
public static void SetPropertyValue(object obj, string propertyName, object value)
{
var param = Expression.Parameter(obj.GetType(), "x");
var property = Expression.Property(param, propertyName);
var valueExpr = Expression.Constant(value);
var assignExpr = Expression.Assign(property, valueExpr);
var lambda = Expression.Lambda<Action<object>>(assignExpr, param);
var setter = lambda.Compile();
setter(obj);
}
这些方法可以通过变量名获取和设置属性。请注意,这些方法可能会带来一定的性能损失,因此在性能敏感的场景中应谨慎使用。
领取专属 10元无门槛券
手把手带您无忧上云