.NET易忘备留 通用函数

1.枚举 

<select id="accountType" name="accountType">
<option value="">---所有---</option>
@foreach (var item in Lib4Net.Comm.EnumHelper.GeMembertValues<PSAccountType>())

     <option value="@((int)item)">@item.GetDescription()</option>
}
</select>

2.获取枚举描述
 /// <summary>
 /// 获取对象描述信息
 /// </summary>
/// <param name="input"></param>
 /// <returns></returns>
 public static string GetDescription(this object input)
{
  if (input == null)
     return string.Empty;
   Type enumType = input.GetType();
   if (!enumType.IsEnum)
  {
    return string.Empty;
      }
      var name = Enum.GetName(enumType, Convert.ToInt32(input));
  if (name == null)
  return string.Empty;
  object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
  if (objs == null || objs.Length == 0)
  {
    return string.Empty;
   }
  else
  {
    DescriptionAttribute attr = objs[0] as DescriptionAttribute;
    return attr.Description;
  }
}

3.字符串显示或处理

/// <summary>
/// 如果数据为空就显示为-
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string ToCustomerString(this object input)
{
  if (input == null)
    return "---";
  else
    return input.ToString();
}


/// <summary>
/// 完成操作:
/// 1.Trim,去掉前后空格
/// 2.将空字符串设置成为null
/// </summary>
/// <param name="input">对象</param>
public static void CustomizeTrim(this object input)
{
  if (input != null)
  {
    Type type = input.GetType();
    PropertyInfo[] infos = type.GetProperties();
    object val = null;
    string strval = null;
    foreach (PropertyInfo info in infos)
    {
      val = info.GetValue(input, null);
      if (val != null)
      {
        if (val.GetType().FullName == typeof(string).FullName)
        {
          strval = val as string;
                            if (string.IsNullOrWhiteSpace(strval))
                            {
                                strval = null;
                            }
                            else
                            {
                                strval = strval.Trim();
                            }
                            if (info.CanWrite)
                            {
                                info.SetValue(input, strval, null);
                            }
        }
      }

            }
  }

}

原文地址:https://www.cnblogs.com/Denny_Yang/p/2682798.html