循环遍历对象属性而无需反射 [英] Loop through object properties without reflection

查看:107
本文介绍了循环遍历对象属性而无需反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类MyModel和一些MyModel对象.

I have class MyModel and some object of MyModel.

我需要无反射的对象的for-loop或foreach属性.如何实现?

I need for-loop or foreach properties of object without reflection. How implemented?

类示例:

public class MyModel
{
    public string Level1_TypeName { get; set; }
    public string Level1_AttrType { get; set; }
    public string Level1_AttrValue { get; set; }
    public string Level2_TypeName { get; set; } 
    public string Level2_AttrType { get; set; }
    public string Level2_AttrValue { get; set; }
    public string Level3_TypeName { get; set; } 
    public string Level3_AttrType { get; set; }
    public string Level3_AttrValue { get; set; }
    public string Level4_TypeName { get; set; } 
    public string Level4_AttrType { get; set; }
    public string Level4_AttrValue { get; set; }
    public string Level5_TypeName { get; set; } 
    public string Level5_AttrType { get; set; }
    public string Level5_AttrValue { get; set; }
    public string Level6_TypeName { get; set; }  
}

推荐答案

我会强烈建议您采取以下两项操作:

I would strongly suggest that you take two actions:

  • 创建一个新类型以封装TypeNameAttrTypeAttrValue
  • 的组合
  • 更改模型以包含该类的集合,而不是几个单独的属性.
  • Create a new type to encapsulate the combination of TypeName, AttrType, AttrValue
  • Change your model to contain a collection of that class rather than several separate properties.

到那时,在不使用反射的情况下对属性进行迭代非常容易...而且您的代码也将更加清晰.

At that point, it will be really easy to iterate over the properties without using reflection... and your code will be much clearer, too.

这篇关于循环遍历对象属性而无需反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆