2011-10-04 71 views
2

我想排序動態對象的Observable集合。我試圖實現IComparer,但它告訴我,我不能實現一個動態接口。我現在卡住了。任何想法如何實現這一點?OrderBy,ObservableCollection <dynamic>,ICompare

我嘗試這樣

list.OrderByDescending(x => x, new DynamicSerializableComparer()); 

然後的IComparer

public class DynamicSerializableComparer : IComparer<dynamic> 
     { 
      string _property; 

      public DynamicSerializableComparer(string property) 
      { 
       _property = property; 
      } 

      public int Compare(dynamic stringA, dynamic stringB) 
      { 
       string valueA = stringA.GetType().GetProperty(_property).GetValue(); 
       string valueB = stringB.GetType().GetProperty(_property).GetValue(); 

       return String.Compare(valueA, valueB); 
      } 

     } 
+0

只實現非通用版本的IComparer –

回答

0

IComparer<dynamic>是,在編譯時,相同IComparer<object>That's why you can't implement it.

嘗試實施IComparer<object>代替,並轉換爲動態。

public class DynamicSerializableComparer : IComparer<object> 
{ 
    string _property; 

    public DynamicSerializableComparer(string property) 
    { 
     _property = property; 
    } 

    public int Compare(object stringA, object stringB) 
    { 
     string valueA = stringA.GetType().GetProperty(_property).GetValue(); 
     string valueB = stringB.GetType().GetProperty(_property).GetValue(); 

     return String.Compare(valueA, valueB); 
    } 

} 
+1

如果對象實際上是動態的(如'ExpandoObject'或某些對象從IronPython的未來)此實現將無法正常工作。 – svick

+0

@Svick:爲什麼呢? –

+0

因爲'Type.GetProperty()'不會給你動態的屬性。 'Type'不知道有關'dynamic'或DLR(我認爲)的任何信息。 – svick

相關問題