根據屬性字串獲取屬性值

.Net菜鸟站發表於2024-11-29

實體物件obj,如 User user=new User(), 屬性名: propertyName 如UserName
根據屬性字串獲取屬性值:
public decimal GetPropertyValue(object obj, string propertyName)
{
if (obj == null)
return 0;
if (string.IsNullOrEmpty(propertyName))
return 0;
Type type = obj.GetType();
PropertyInfo property = type.GetProperty(propertyName);
if (property == null)
return 0;
return System.Convert.ToDecimal(property.GetValue(obj));
}

相關文章