2016-05-22 10 views
1

私は2つのクラスがあります。反射と再帰 - StackOverflowExceptionが

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; } 
} 

そして、2つのインスタンス:

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" 
     } 
    } 
}; 

私は2つのインスタンスのすべてのプロパティを比較する一つの方法があります。

をしかし、私がプロパティProductに行くとき、私はStackOverflowExceptionを生成しました。どうして ?配列の場合はどのようにループするのですか?

EDIT:リストを使用すると、StackOverflowExceptionではなく、System.Reflection.TargetParameterCountExceptionとなります。どのようにループそれは

+0

なぜスタックオーバーフローが発生しているのかをコードにデバッグしましたか? –

+0

これは重複のようです。 http://stackoverflow.com/questions/3747572/how-do-i-deal-with-arrays-using-reflection –

+0

この提案された回答は役立ちます:http://stackoverflow.com/a/4879978/6256551 –

答えて

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メソッドを使用すると、Productプロパティと同じSyncRootプロパティに到達します。 これでループを離れることはできません。 (SyncRootはSyncRootプロパティが自分自身を指しているので)