使用foreach为类中定义的每个字段(相同类型)执行操作?

时间:2013-01-15 18:49:53

标签: c# foreach

例如,是否可以使用foreach语句为类中的每个字符串执行操作?

foreach (string s in <class>)

就像我可以在AppSettings中使用它一样吗?

foreach (string key in ConfigurationManager.AppSettings)

如果不可能,还有其他类似方法吗?

2 个答案:

答案 0 :(得分:2)

您可以使用名称空间System.ReflectionSystem.Linq

foreach (var pi in typeof(<YourClass>).GetProperties().Where(p => p.PropertyType.Equals(typeof(string))))
{
    pi.SetValue(targetObject, value);
}

答案 1 :(得分:0)

   public  class TestClass {
        public string String1 { get; set; }
        public string String2 { get; set; }
        public int Int1 { get; set; }


        public TestClass() {
            String1 = "Frank";
            String2 = "Borland";
            foreach (var item in this.GetType().GetProperties().Where(p => p.PropertyType.Equals(typeof(string)))) {
                string value = item.GetValue(this, null) as string;
                Debug.WriteLine("String: {0} Value: {1}", item.Name, value);
            }
        }
    }

打印出类实例字符串的名称和值。