例如,是否可以使用foreach语句为类中的每个字符串执行操作?
foreach (string s in <class>)
就像我可以在AppSettings中使用它一样吗?
foreach (string key in ConfigurationManager.AppSettings)
如果不可能,还有其他类似方法吗?
答案 0 :(得分:2)
您可以使用名称空间System.Reflection
和System.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);
}
}
}
打印出类实例字符串的名称和值。