C#属性数组 [英] C# array of properties
本文介绍了C#属性数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个get属性,它们希望像函数数组一样循环遍历.我希望能够做这样的事情
I have several get properties that I would like to be able to loop through like an array of functions. I would like to be able to do something like this
public int prop1 { get; }
public string prop2 { get; }
public int[] prop3 { get; }
public int prop4 { get; }
public string prop5 { get; }
public string prop6 { get; }
Func<var> myProperties = { prop1, prop2, prop3, prop4, prop5, prop6 };
ArrayList myList = new ArrayList();
foreach( var p in myProperties)
{
myList.Add(p);
}
这段代码很破损,但是我认为它传达了我想要做的事情的想法.有人知道我该怎么做到吗?
This code is very broken, but I think it conveys the idea of what I would like to be able to do. Anyone know how I can achieve this?
推荐答案
您可以使用反射来访问您类型中的属性:
You could use reflection to access the properties within your type:
class MyType
{
public int prop1 { get; }
public string prop2 { get; }
public int[] prop3 { get; }
public int prop4 { get; }
public string prop5 { get; }
public string prop6 { get; }
public List<string> GetAllPropertyValues()
{
List<string> values = new List<string>();
foreach (var pi in typeof(MyType).GetProperties())
{
values.Add(pi.GetValue(this, null).ToString());
}
return values;
}
}
请注意,反射速度较慢,如果有更好的方法,则不应使用此功能.例如,当您知道只有6个属性时,只需逐一浏览它们即可.
Note that reflection is slow and you shouldn’t use this if there is a better way. For example when you know that there are only 6 properties, just go through them individually.
这篇关于C#属性数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文