79 lines
2.5 KiB
C#
79 lines
2.5 KiB
C#
using System.Reflection;
|
|
|
|
namespace YLErp.Helpers
|
|
{
|
|
public static class TypeHelper
|
|
{
|
|
public static bool IsNullableType(Type type)
|
|
{
|
|
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>);
|
|
}
|
|
|
|
public static void SetPropValue<TModel>(TModel model, string propName, object value) where TModel : class
|
|
{
|
|
if (model == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(model));
|
|
}
|
|
var type = model.GetType();
|
|
|
|
if (string.IsNullOrWhiteSpace(propName))
|
|
{
|
|
throw new ArgumentException($"参数{propName}有误");
|
|
}
|
|
var dotIndex = propName.IndexOf(".");
|
|
if (dotIndex == -1)
|
|
{
|
|
var prop = type.GetProperty(propName, BindingFlags.Instance | BindingFlags.Public);
|
|
if (prop == null)
|
|
{
|
|
throw new ArgumentOutOfRangeException(propName);
|
|
}
|
|
|
|
object objVal;
|
|
if (TryChangeType(value, prop.PropertyType, out objVal))
|
|
{
|
|
prop.SetValue(model, objVal);
|
|
return;
|
|
}
|
|
throw new ArgumentException("value数据类型有误");
|
|
}
|
|
|
|
var tempPropName = propName.Substring(0, dotIndex);
|
|
var tempProp = type.GetProperty(tempPropName, BindingFlags.Instance | BindingFlags.Public);
|
|
if (tempProp == null)
|
|
{
|
|
throw new ArgumentOutOfRangeException(tempPropName);
|
|
}
|
|
|
|
var tempPropObj = tempProp.GetValue(model);
|
|
if (tempPropObj == null)
|
|
{
|
|
tempPropObj = Activator.CreateInstance(tempProp.PropertyType);
|
|
tempProp.SetValue(model, tempPropObj);
|
|
}
|
|
|
|
SetPropValue(tempPropObj, propName.Substring(dotIndex + 1), value);
|
|
}
|
|
|
|
public static bool TryChangeType(object value, Type targetType, out object newValue)
|
|
{
|
|
if (IsNullableType(targetType))
|
|
{
|
|
targetType = Nullable.GetUnderlyingType(targetType);
|
|
}
|
|
|
|
newValue = null;
|
|
try
|
|
{
|
|
newValue = Convert.ChangeType(value, targetType);
|
|
return true;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|