控制反射属性值返回顺序的最佳方法是什么?
我有一个类继承了另一个类。我想使用反射来循环属性并将值写入文件。没问题。只是我想控制属性的写出顺序。有没有一种干净的方法来做到这一点?现在,问题1是子类中的属性写出,然后父类中的属性写出。而且,我可能想跳过一些属性或只是重新排序它们。
现在这是我的代码......
foreach (PropertyInfo bp in t.GetProperties())
{
Type pt = bp.PropertyType;
if ((pt.IsArray) && pt.FullName == "System.Char[]")
{
char[] caPropertyValue;
caPropertyValue = (char[])(bp.GetValue(oBatch, null));
string strPropertyValue = new string(caPropertyValue);
myBatch.Add(strPropertyValue);
}
}
I have one class that inherits another. I want to use reflection to cycle through the properties and write the values to a file. No problem. Except that I want to control the order in which the properties write out. Is there a clean way to do this? Right now, problem 1 is that the properties in the the subclass write out and THEN the proepries in the parent class write out. But also, I may want to skip some properties or just reorder them.
Here is my code now...
foreach (PropertyInfo bp in t.GetProperties())
{
Type pt = bp.PropertyType;
if ((pt.IsArray) && pt.FullName == "System.Char[]")
{
char[] caPropertyValue;
caPropertyValue = (char[])(bp.GetValue(oBatch, null));
string strPropertyValue = new string(caPropertyValue);
myBatch.Add(strPropertyValue);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是按照名字的字母顺序对它们进行排序。您还可以按所属类别对它们进行分组,然后按名称对每个组进行排序。 LINQ 使此类操作相对简单:
或者
The easiest way would be to order them by their name - alphabetically. You could also group them by class they belong to and then order each group by name. LINQ makes such operations relatively easy:
or
您可以创建自己的属性,即“OrderAttribute”并将其放置在属性上
例如,
在排序例程中,您可以通过 pi.GetCustomAttribute() 检查顺序属性值,然后对 pi 进行排序。
You could create your own Attribute i.e. '''OrderAttribute''' and place it over property
such as
in the sorting routine you can check order attribute value via pi.GetCustomAttribute() and sort pi's over it.
查看 GetProperties 语法。有一个参数告诉它您是否只需要当前类的属性,或者按照您的要求,需要整个继承链的属性。您必须遍历类结构才能找到每个级别的属性。
check out the GetProperties syntax. There's a parameter to tell it whether or not you want attributes for the current class only or, as you're asking, for the entire inheritance chain. You will have to walk your class structure to find the attributes at each level.