Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用反射从Property.GetValue返回对象列表_C#_Reflection - Fatal编程技术网

C# 使用反射从Property.GetValue返回对象列表

C# 使用反射从Property.GetValue返回对象列表,c#,reflection,C#,Reflection,使用PropertyInfo.GetValue方法时,我需要检索对象列表。 我不知道它将是什么类型的列表。我的代码如下所示: public IEnumerable<Error> FindErrors(object obj) { var errors = new List<Error>(); errors.AddRange(Validate(obj)); List<PropertyInfo>

使用PropertyInfo.GetValue方法时,我需要检索对象列表。 我不知道它将是什么类型的列表。我的代码如下所示:

    public IEnumerable<Error> FindErrors(object obj)
    {
        var errors = new List<Error>();

        errors.AddRange(Validate(obj));


        List<PropertyInfo> properties = obj.GetType().GetProperties().Where(p => !p.PropertyType.IsByRef).ToList();


        foreach (var p in properties)
        {
            if (IsList(p))
            {
                // This line is incorrect?  What is the syntax to get this to be correcT?????
                List<object> objects = p.GetValue(obj, null);

                foreach (object o in objects)
                {
                    errors.AddRange(FindErrors(o));
                }
            }
            else
            {
                errors.AddRange(FindErrors(p.GetValue(obj, null)));
            }
        }


        return errors;
    }
public IEnumerable查找错误(object obj)
{
var errors=新列表();
错误。添加范围(验证(obj));
List properties=obj.GetType().GetProperties().Where(p=>!p.PropertyType.IsByRef).ToList();
foreach(属性中的var p)
{
if(IsList(p))
{
//这一行是不正确的?用什么语法使它正确?????
List objects=p.GetValue(obj,null);
foreach(对象中的对象o)
{
错误。AddRange(FindErrors(o));
}
}
其他的
{
errors.AddRange(FindErrors(p.GetValue(obj,null));
}
}
返回错误;
}

我的问题是,我不确定获取该列表的语法应该是什么,因为该行代码当前不正确。如何获取对象列表?

并非每个
列表都是
列表。您可能应该检查该类型是否实现了非泛型
IList
,并改用它:

var objects = p.GetValue(obj, null) as IList;
if(objects != null) {...}

您可以通过
IList

Hi Marc!谢谢,这正是我要找的!它似乎工作得很好。