【问题标题】:Reflection and recursion in array - StackOverflowException数组中的反射和递归 - StackOverflowException
【发布时间】:2016-09-19 10:31:35
【问题描述】:

我有两个班级:

public class Customer
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public bool isActif { get; set; }

    public Product[] Product { get; set; }
}

public class Product
{
    public string Id { get; set; }
}

还有两个实例:

Customer Customer1 = new Customer
{
    FirstName = "FirstName1",
    LastName = "LastName1",
    isActif = true,
    Product = new Product[]
    {
        new Product()
        {
            Id = "1"
        }
    }
};

Customer Customer2 = new Customer
{
    FirstName = "FirstName2",
    LastName = "LastName2",
    isActif = false,
    Product = new Product[]
    {
        new Product()
        {
            Id = "2"
        }
    }
};

我有一种方法可以比较两个实例的所有属性:

但是当我到达Product 属性时,我生成了一个StackOverflowException。为什么 ?如果它是一个数组,如何循环该属性?

编辑:当我使用列表时,不是StackOverflowException,而是System.Reflection.TargetParameterCountException。如果是数组,如何循环属性

【问题讨论】:

标签: c# exception recursion reflection stack-overflow


【解决方案1】:

在:

foreach (PropertyInfo propertyInfo in
             objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(x => x.CanRead))

改变你的 where 条件:

 .Where(x => x.CanRead && x.Name != "SyncRoot")

SyncRoot documentation

如果你这样做:

Console.WriteLine(Customer1.Product.Equals(Customer1.Product.SyncRoot));

您将看到 Customer1.Product 等于它的 SyncRoot 属性。 因此,当您在 Product 属性上使用 AreEquals 方法时,您将到达 SyncRoot 属性,该属性与 Product 属性相同。 那么你将永远无法离开循环。 (因为 SyncRoot 有一个指向自身的 SyncRoot 属性)

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2013-03-02
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 2013-09-06
    • 2022-01-24
    相关资源
    最近更新 更多