2014-02-06 69 views
4

使用反射我有一個工具,得到一個類的屬性:屬性在一個特定的順序

foreach (MemberInfo member in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)) 
{ 
    WriteValue(streamWriter, member.Name); 
} 

有沒有辦法問「的GetProperties」返回的MemberInfo在它們在類中定義的順序。我嚴重懷疑它,但我想我會問。

class Person 
{ 
    public int Id { get; set; } 
    public int Age { get; set; } 
} 

我想獲得這個訂單的MemberInfo當時:身份證,年齡

+0

也許你已經把問題分成了一個明顯的和不可能的部分。你需要做什麼? –

回答

2

更新 [在你自己的discresion因爲這些都是很明顯微軟的IMPL細節,這可能會在未來的版本中改變Caution:使用方法】:單seems to work too

我觀察到使用MS編譯器,因爲consitent行爲v3.5當我偶然發現這個:

using System; 
using System.Linq; 
using System.Reflection; 


namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     {  
      typeof(Test).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) 
       .OrderBy(member => member.MetadataToken).ToList() 
       .ForEach(member => Console.WriteLine(member.Name)); 

      Console.ReadLine(); 
     } 
    } 

    public class Test 
    { 
     public int SecondProperty { get; set; } 
     public int FirstProperty { get; set; } 

    } 
} 
1

不,自動性能沒有。您可以使用調試符號按照聲明的順序獲取方法,並且由於屬性獲取器是方法,因此您可以(通過一些工作)按聲明順序獲取具有顯式獲取器(或setter)的屬性列表,但可以使用自動屬性獲取器沒有源代碼,因此沒有調試符號來指示它們的位置。至於CLI元數據,編譯器沒有義務按照聲明的順序放置它們,並且由於反射僅依賴於元數據,因此不能用於此目的。