【问题标题】:How to know if a property is a type of List<MyClass>?如何知道属性是否是 List<MyClass> 的类型?
【发布时间】:2018-07-03 07:03:04
【问题描述】:

我在这些课程中有这个。

public class MyClass:BaseClass
{ }

public class BaseClass
{ }

public class CollectionClass
{
   public string SomeProperty {get; set;}

   public List<MyClass> Collection {get; set;}
}

在我的代码中,我想知道某个对象(例如CollectionClass)中的属性是否是List&lt;BaseClass&gt; 的类型,如果属性是List&lt;MyClass&gt; 的类型,我也想返回true。下面的代码解释了这一点。

public bool ContainsMyCollection(object obj)
{
   foreach(var property in obj.GetType().GetProperties())
   {
      //  Idk how to accomplish that
      if(property isTypeof List<BaseClass>)
         return true;
   }
   return false
}

【问题讨论】:

  • 我写了一个答案,但我想我误解了,所以我现在删除了它。你知道List&lt;MyClass&gt; 不是List&lt;BaseClass&gt; 的派生类型,对吧?例如,List&lt;BaseClass&gt; a = new List&lt;MyClass&gt;() 不起作用。
  • if(property.PropertyType == typeof(List&lt;BaseClass&gt;)) 但不清楚你真正想要实现什么
  • 也许更好地解释为什么你想要这个而不是你想要什么。

标签: c# reflection collections


【解决方案1】:

您需要检查您是否有List&lt;&gt; 的封闭类型。可以这样做:

if(property.PropertyType.IsGenericType
    && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))

然后您必须检查泛型参数(List&lt;T&gt;T 部分)是否可分配给您的基本类型:

if (typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))

把这些放在一起,你会得到这个:

public bool ContainsMyCollection(object obj)
{
   foreach(var property in obj.GetType().GetProperties())
   {
      //  Idk how to accomplish that
      if(property.PropertyType.IsGenericType 
         && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)
         && typeof(BaseClass).IsAssignableFrom(property.PropertyType.GetGenericArguments()[0]))
      {
          return true;
      }
   }
   return false;
}

请注意,如 cmets 中所述,List&lt;MyClass&gt; 不是从 List&lt;BaseClass&gt; 派生的,即使 MyClass 是从 BaseClass 派生的。因此,例如,List&lt;BaseClass&gt; a = new List&lt;MyClass&gt;(); 将失败。这超出了你的问题范围,但我想我会提醒你,以防你还不知道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2015-02-14
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多