2017-03-29 61 views
1

我需要確定List是否包含ICollection,其中T是動態的,並且在編譯時不知道。繼承人我的代碼,以便更好地理解我的意思:確定列表<Type>是否包含ICollection <dynamic>

private void RefreshDataSource<T>(ICollection<T> dataSource) where T : IEquatable<T> 
{ 
    dynamic row = view.GetFocusedRow(); 
    //Get's the focused row from a DevExpress-Grid 
    //I don't know the type because it's MasterDetail and the view can be a DetailView. In this case type T isn't the underlying type. 

    //Getting all Properties 
    var dummy = dataSource.FirstOrDefault(); 
    var props = dummy.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList(); 

    //Now comes the real problem, I need to determine the Detail Datasource 
    //and to do this I want to check if there is a Property from ICollection<typeof(row)> 

    //How can I check on ICollection<typeof(row)> instead of row 
    //IsAssignableFrom would better fit my needs but I don't get how to solve my problem with it. 
    var detailSource = props.FirstOrDefault(p => p.PropertyType.IsInstanceOfType(row)); 
} 

的代碼被打破的重要點,因此,如果......不知道。在你的眼裏沒有意義;-)。有什麼方法可以檢查ICollection<T>哪裏T是一個動態類型,只是在運行時知道?

注意,由於MasterDetail關係,給定的T在方法之上並不是行的類型!

UDPATE

我想我需要澄清我的需要。把我想象成一個網格。我得到的是一個ICollection<T>的數據源,每一行都由T的一個對象表示。現在我使用MasterDetail關係,以便T代表網格中的一個MasterRow。 DetailView的行由任何ICollection<AnyClass>表示,它被定義爲T上的屬性。

現在我需要從T中確定這個ICollection<AnyClass>屬性,而不必知道AnyClass在編譯時是什麼。因爲我知道我的DetailView可以這樣做:

dynamic row = view.GetFocusedRow(); 

所以排式AnyClass,並在運行聞名。但是我怎麼能在T的PropertyCollection中找到這個ICollection<AnyClass>屬性?這是我的問題。

+0

我喜歡反思,如果你正在描述確切的問題,可以幫助你。你想知道ICollection 中的「T」的類型名稱嗎? –

+0

@Karthik AMR不,我的代碼的最後一行是重要的。在那裏,我想檢查道具是否包含一個條目,其中p => p.PropertyType是ICollection類型 Sebi

+0

您是否確實指'動態'或T'? – CSharpie

回答

1

一般情況下,這應該做

.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<dynamic>)); 

的情況下,你的意思T而不是dynamic,簡單的更換。

.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<T>)); 

如果你想T和它的亞型,它變得更加複雜

.GetType().GetInterfaces().Any(intf => intf.IsGenericType && 
             intf.GetGenericTypeDefinition() == typeof(ICollection<>) && 
             intf.GetGenericArguments()[0].IsAssigneableFrom(typeof(T))); 

編輯既然你calrified你真正需要的:

.GetType().GetInterfaces().Any(intf => intf.IsGenericType && 
             intf.GetGenericTypeDefinition() == typeof(ICollection<>)); 

這可能是更簡單,但ICollection<T>不執行ICollection

+0

所以如果道具包含Entry集合並且行在運行時是MyClass,那麼這將是真實的嗎?我會認爲,必須有一個財產ICollection 比... – Sebi

+0

@塞比它應該解決你的問題。 –

+0

我不確定這將會起什麼作用 - 'dynamic'是一組編譯器技巧,並且這種對象的實際聲明類型是'object' - 所以我認爲'typeof'將生成與typeof( ICollection )'會 - 所以一些誤報是可能的。 –

相關問題