C# 遍历枚举和遍历类

  //1、遍历枚举
   foreach (NameEnum item in Enum.GetValues(typeof(NameEnum)))
        {
            string name= item.ToString();              
        }
 //2、遍历类
 public class userInfo
    {
        public string customerName { get; set; }
        public string sex { get; set; }
        public string age { get; set; }
        public string time { get; set; }
        public string quality { get; set; }
        public string siteName { get; set; }
    }
   userInfo user = new userInfo();
            System.Reflection.PropertyInfo[] properties = 
   user.GetType().GetProperties(System.Reflection.BindingFlags.Instance | 
   System.Reflection.BindingFlags.Public);
            if (properties.Length <= 0)
            {
                throw new Exception("光谱透过率类字段长度为空");
            }
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                string name = item.Name;
                item.SetValue(user, "111", null);
            }
         //3、遍历类获取属性值
 System.Reflection.PropertyInfo[] properties = BaseClass.Datas.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
        if (properties.Length <= 0)
        {
            throw new Exception("类属性长度为零");
        }
       
        foreach (System.Reflection.PropertyInfo item in properties)
        {
            if (item.Name.Contains("State")) continue;
            var value = BaseClass.Datas.GetType().GetProperty(item.Name).GetValue(BaseClass.Datas, null).ToString();
            if(value == "名称")
            {
               var name = item.Name.Substring(5, item.Name.Length - 5);
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容