在声明中使用反射为了获取性能 [英] Get properties in order of declaration using reflection

查看:131
本文介绍了在声明中使用反射为了获取性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用它们在类中声明的顺序反映的所有属性。根据MSDN使用的GetProperties()

当订单无法保证

  

的的GetProperties方法不会在特定的返回特性
  顺序,如按字母顺序或声明顺序。


但我读过,有一种变通方法由 MetadataToken 排序的属性。所以我的问题是,是安全的呢?我似乎无法找到它在MSDN上的任何信息。还是有解决这个问题的任何其他方式?

我的当前实现如下所示:

  VAR道具= typeof运算(T)
   .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic可)
   .OrderBy(X => x.MetadataToken);


解决方案

据的 MSDN MetadataToken 是一个模块内独特的 - 没有什么话说,它保证任何顺序可言

即使它表现你想要的方式,这将是实现特定的,可以不另行通知随时更改。

看到这个老 MSDN博客条目

我会强烈建议从这样的实现细节的任何dependeny走就走 - 见从马克Gravell 这个答案<。 / p>

如果你需要在编译时的东西,你可以看看<一个href=\"http://blogs.msdn.com/b/visualstudio/archive/2011/10/19/introducing-the-microsoft-roslyn-ctp.aspx\"相对=nofollow>罗斯林(虽然它是在一个非常早期的阶段)。

I need to get all the properties using reflection in the order in which they are declared in the class. According to MSDN the order can not be guaranteed when using GetProperties()

The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order.

But I've read that there is a workaround by ordering the properties by the MetadataToken. So my question is, is that safe? I cant seem find any information on MSDN about it. Or is there any other way of solving this problem?

My current implementation looks as follows:

var props = typeof(T)
   .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
   .OrderBy(x => x.MetadataToken);

解决方案

According to MSDN MetadataToken is unique inside one Module - there is nothing saying that it guarantees any order at all.

EVEN if it did behave the way you want it to that would be implementation-specific and could change anytime without notice.

See this old MSDN blog entry.

I would strongly recommend to stay away from any dependeny on such implementation details - see this answer from Marc Gravell.

IF you need something at compile time you could take a look at Roslyn (although it is in a very early stage).

这篇关于在声明中使用反射为了获取性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆