namespace NPin.Framework.Core.Helper;

public static class ReflectHelper
{
    /// <summary>
    /// 反射获取对象属性值(string)
    /// </summary>
    /// <param name="fieldName"></param>
    /// <param name="obj"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static string? GetModelValue(string fieldName, object obj)
    {
        try
        {
            var typ = obj.GetType();
            object o = typ.GetProperty(fieldName).GetValue(obj, null);
            if (o == null)
            {
                return null;
            }

            var value = Convert.ToString(o);
            if (string.IsNullOrEmpty(value))
            {
                return null;
            }

            return value;
        }
        catch (Exception e)
        {
            throw e;
        }
    }

    /// <summary>
    /// 反射设置对象属性值
    /// </summary>
    /// <param name="fieldName"></param>
    /// <param name="value"></param>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static bool SetModelValue(string fieldName, object value, object obj)
    {
        try
        {
            var typ = obj.GetType();
            typ.GetProperty(fieldName)?.SetValue(obj, value, null);
            return true;
        }
        catch (Exception e)
        {
            throw e;
        }
    }
}