如何遍历所有"公共字符串"在.NET类的属性 [英] How to iterate all "public string" properties in a .net class
本文介绍了如何遍历所有"公共字符串"在.NET类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以说我有一个包含类的各种一些属性和方法的一些随机的cs文件。
我如何可以遍历所有这些公共字符串属性的名称(字符串)?
Example.cs:
公共类实例
{
公共字符串FIELDA {获取;集;}
公共字符串FieldB {获取;集;}
私人消息1字符串{获取;集;}
公众诠释someInt {获取;集;}
公共无效的button1_Click(对象发件人,EventArgs的)
{
MESSAGE1 =字段:;
的ForEach(在this.GetPublicStringProperties字符串propertyName的())
{
MESSAGE1 + = propertyName的+,;
}
消息1 // =字段:字段1,字段2
}
私人字符串[] GetPublicStringProperties()
{
//什么我们把这里返回{字段1,字段2}?
}
}
解决方案
私有的String [] GetPublicStringProperties()
{
返回this.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
。凡(PI => pi.PropertyType == typeof运算(字符串))
。选择(PI => pi.Name)
.ToArray();
}
Lets say I have some random .cs file containing a class with some properties and methods of all sorts.
How can I iterate the names (as strings) of all these public string properties?
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();
}
这篇关于如何遍历所有"公共字符串"在.NET类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文