zoukankan      html  css  js  c++  java
  • 使用反射将string转换为enum

    很简单就一句话的代码。

    1                             if (item.PropertyType.IsEnum)
    2                             {
    3                                 item.SetValue(obj, Enum.Parse(item.PropertyType, val), null);
    4                             }

    怎么样就是这么简单。哈哈哈...

    贴出完整Demo。

     1             public static void SetObjValue(object obj, string[] valueList)
     2             {
     3                 var objProperties = obj.GetType().GetProperties();
     4                 foreach (var item in objProperties)
     5                 {
     6                     var itemName = item.Name + ":";
     7                     var mathCount = valueList.Where(p => p.Contains(itemName)).Count();
     8                     if (mathCount == 1)
     9                     {
    10                         var val = valueList.Single(p => p.Contains(itemName));
    11                         val = val.Replace(itemName, "");
    12                         try
    13                         {
    14                             item.SetValue(obj, val, null);
    15                         } 
    16                         catch
    17                         {
    18                             if (item.PropertyType.IsEnum)
    19                             {
    20                                 item.SetValue(obj, Enum.Parse(item.PropertyType, val), null);
    21                             }
    22                         }
    23                     }
    24                 }
    25             }
    View Code
  • 相关阅读:
    find
    fdisk
    falcon-eye
    ethtools
    e2fsck
    dpkg
    declare
    df
    debconf-utils
    区块链从零开始做开发(0):hyperledger Fabric2.3安装
  • 原文地址:https://www.cnblogs.com/FlyStupidBird/p/8042818.html
Copyright © 2011-2022 走看看