如何知道属性是否为列表类型<MyClass>?



我在这些类中有这个。

public class MyClass:BaseClass
{ }
public class BaseClass
{ }
public class CollectionClass
{
public string SomeProperty {get; set;}
public List<MyClass> Collection {get; set;}
}

在我的代码中,我想找出某个对象中的属性(例如CollectionClass( 是一种List<BaseClass>如果属性是一种List<MyClass>类型,我也想返回 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<>。这可以像这样完成:

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

然后你必须检查泛型参数(List<T>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;
}

请注意,正如注释中所解释的,List<MyClass>不是从List<BaseClass>派生的,即使MyClass派生自BaseClass。因此,例如,List<BaseClass> a = new List<MyClass>();将失败。这超出了你的问题范围,但我想如果你还不知道,我会给你一个提示。

最新更新