如何迭代.net类中的所有“公共字符串”属性

假设我有一些随机的.cs文件,其中包含一个具有各种属性和方法的类。

如何迭代所有这些公共字符串属性的名称(作为字符串)?

Example.cs:

Public class Example { public string FieldA {get;set;} public string FieldB {get;set;} private string Message1 {get;set;} public int someInt {get;set;} public void Button1_Click(object sender, EventArgs e) { Message1 = "Fields: "; ForEach(string propertyName in this.GetPublicStringProperties()) { Message1 += propertyName + ","; } // Message1 = "Fields: Field1,Field2" } private string[] GetPublicStringProperties() { //What do we put here to return {"Field1", "Field2"} ? } } 

 private string[] GetPublicStringProperties() { return this.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(pi => pi.PropertyType == typeof(string)) .Select(pi => pi.Name) .ToArray(); } 

您可以使用TypeGetProperties方法:

 GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 

这将为您提供一组PropertyInfo对象,每个属性对应一个。

您可以通过检查以下内容来检查属性是否为string属性:

 property.PropertyType == typeof(string) 

要获取属性的名称,请使用property.Name

 var publicStringProperties = from property in GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) where property.PropertyType == typeof(string) select property.Name;