尝试使用反射查找不为空的对象中的所有集合 [英] Trying to find all collections in an object not null with reflection

查看:45
本文介绍了尝试使用反射查找不为空的对象中的所有集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个通用的单元测试方法,以确保我们所有的对象都在初始化它们作为构造函数集合的属性.我没有手动检查每个属性的断言,然后考虑是否修改了类对象,我想使用反射.问题在于集合,并不仅仅是List,而是类的类副本,然后继承List.

I am trying to build a generic unit test method, to make sure all of our objects are initiliazing their properties that are collections on the constructor. I instead of manually checking with assert on each property, and then thinking ahaed if a class object is modified, I wanted to use reflection. The problem is that the collections, and not just List, but a class copy of the class, and then inherit List.

所以,我们可能有如下内容:

So, we may have somthing like the following:

public class PaymentType
{
   int Id{get;set;}
   PaymentTypeCollection PaymentTypeCollection {get;set;}

}

public class PaymentTypeCollection : List<PaymentType>
{
   //som ecustom stuff here

}

现在的问题是,当您从 PaymentType 类中迭代对象的属性,并尝试使用以下检查执行反射方法时,它返回 false,并且可以理解.

Now the problem is that when you itterate over the properties of the object from class PaymentType, and try to do a reflection method with the following check, it comes back false, and understandably.

foreach (var prop in objectType.GetProperties())
        {
            // test if property is IEnumerable<T>? This comes back as false
            if (typeof(IEnumerable<>).IsAssignableFrom(prop.PropertyType))
            {
               //do stuff here
            }
        }

我该如何解决这个问题.我需要查看该属性是否继承了 IEnumerable?因为类型实际上是 PaymentTypeColelction.我将如何处理?

How could I go about the issue. I need to see if the property, is then inheriting IEnumerable? Since the type would actually be PaymentTypeColelction. How would I handle that?

提前致谢.

推荐答案

使用非通用的 IEnumerable.泛型的IEnumerable实现了IEnumerable,不用担心类型参数.

Use the non-generic IEnumerable. The generic IEnumerable<out T> implements IEnumerable, and you don't have to worry about type arguments.

if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType))
{
    //do stuff here
}

但是要小心,例如string也实现了IEnumerable,所以你的方法也会找到string属性.

But be careful, for example string also implements IEnumerable<char>, so your method will also find string properties.

这篇关于尝试使用反射查找不为空的对象中的所有集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆