确定List <type>是否包含ICollection <dynamic>

时间:2017-03-29 07:18:06

标签: c# generics

我需要确定List是否包含ICollection,其中T是动态的,在编译时是不知道的。继承我的代码以更好地理解我的意思:

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>的DataSource,每一行都由T的对象表示。现在我正在使用MasterDetail关系,以便T只代表Grid中的一个MasterRow。 DetailView的行由任何ICollection<AnyClass>表示,它被定义为T上的属性。

现在我需要从T中确定这个ICollection<AnyClass>属性,而不知道编译时AnyClass是什么。因为我知道DetailView我可以这样做:

dynamic row = view.GetFocusedRow();

因此,row属于AnyClass类型,并且在运行时中已知。但是如何在T的PropertyCollection中找到这个ICollection<AnyClass>属性?这是我的问题。

1 个答案:

答案 0 :(得分: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)));

编辑由于您对实际需要的内容进行了调整:

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

它可能更简单,但ICollection<T>未实现ICollection