#region 根据属性名获取或设置值
/// <summary>
/// 根据属性名获取值
/// </summary>
/// <param name="model">实体</param>
/// <param name="modelName">属性名</param>
/// <returns></returns>
public static object GetValueByModelName(object model, string modelName)
{
try
{
object currentModel = null;
PropertyInfo property = GetPropertyInfoByModelName(model, modelName, ref currentModel);
if (property != null && currentModel != null)//属性和当前属性对应的model不为空
{
return property.GetValue(currentModel, null) ?? "";
}
else
{
return "";
}
}
catch (Exception ex)
{
LogHelper.WriteLog($"获取{modelName}异常", ex);
return "";
}
}
/// <summary>
/// 根据属性名设置属性值
/// </summary>
/// <param name="model">实体</param>
/// <param name="modelName">属性名</param>
/// <param name="setValue">设置的值</param>
public static void SetValueByModelName(object model, string modelName, string setValue)
{
try
{
object currentModel = null;
PropertyInfo property = GetPropertyInfoByModelName(model, modelName, ref currentModel);
if (property != null && currentModel != null)//属性和当前属性对应的model不为空
{
if (property.PropertyType.Name == "CData")
{
CData cData = new CData();
cData.Value = setValue.ToString();
property.SetValue(currentModel, cData, null);
}
else
{
property.SetValue(currentModel, setValue, null);
}
}
}
catch (Exception ex)
{
LogHelper.WriteLog($"设置{modelName}值异常", ex);
}
}
/// <summary>
/// 根据实体属性名获取属性信息
/// </summary>
/// <param name="model">实体</param>
/// <param name="modelName">属性名</param>
/// <param name="currentModel">属性对应的实体</param>
/// <returns></returns>
public static PropertyInfo GetPropertyInfoByModelName(object model, string modelName, ref object currentModel)
{
PropertyInfo result = null;//返回结果
try
{
if (model != null && !string.IsNullOrEmpty(modelName))//实体和需要获取的属性名都不为空
{
//先直接找,是否有改属性
PropertyInfo property = model.GetType().GetProperty(modelName);
if (property != null)
{
currentModel = model;
return property;
}
foreach (var item in model.GetType().GetProperties())//遍历实体里的所有公开属性
{
//不是基元类型 && 是类 && 不是泛型 && 命名空间不是System.开头的
if (
!(
item.PropertyType.IsPrimitive
|| item.PropertyType.IsEnum
|| item.PropertyType.Equals(typeof(string))
|| item.PropertyType.Equals(typeof(CData))
|| item.PropertyType.Equals(typeof(DateTime))
|| item.PropertyType.Equals(typeof(Module))
)
&& item.PropertyType.IsClass
&& !(item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
&& !item.PropertyType.FullName.StartsWith("System.")
)
{
PropertyInfo ItmeProperty = model.GetType().GetProperty(item.Name);
if (ItmeProperty != null)
{
var objModel = ItmeProperty.GetValue(model, null);
result = GetPropertyInfoByModelName(objModel, modelName, ref currentModel);
}
if (result != null)
{
return result;
}
}
}
return null;
}
else
{
//如果出现没有实例化子表的情况,会返回null,所以在此处理一下
result = null;
}
return result;
}
catch (Exception ex)
{
LogHelper.WriteLog($"获取{modelName}异常", ex);
}
return result;
}
#endregion
根据属性名获取或设置值
于 2023-09-01 16:20:28 首次发布