こんにちは。
C#でthisとforeachの組み合わせで悩んでいます。
Windows10, VisualStudio2015です。
multi windowのprogramを作っていて、windowのtop, left, width, heightをすべて保存しようというのです。
困っているのはEqualsの実装です。
C#
1using System.Windows; 2 3namespace multiwindows 4{ 5 public class WindowProperty 6 { 7 public double Top { get; set; } 8 public double Left { get; set; } 9 public double Width { get; set; } 10 public double Height { get; set; } 11 } 12}
として。
C#
1namespace multiwindow 2{ 3 using System.Collections.Generic; 4 5 public class UserSetting 6 { 7 public WindowProperty MainWindowProperty { get; set; } 8 public WindowProperty SettingWindowProperty { get; set; } 9 public WindowProperty ToolWindowProperty { get; set; } 10 public WindowProperty AllMapWindowProperty { get; set; } 11 public WindowProperty StatusWindowProperty { get; set; } 12 13 public override int GetHashCode() 14 { 15 return 1; 16 } 17 18 public override bool Equals(object obj) 19 { 20 if (this == obj) return true; 21 if (obj == null) return false; 22 if (this.GetType() != obj.GetType()) 23 return false; 24 25 var other = (UserSetting)obj; 26 if (this.MainWindowProperty != other.MainWindowProperty) return false; 27 if (this.SettingWindowProperty != other.SettingWindowProperty) return false; 28 if (this.ToolWindowProperty != other.ToolWindowProperty) return false; 29 if (this.AllMapWindowProperty != other.AllMapWindowProperty) return false; 30 if (this.StatusWindowProperty != other.StatusWindowProperty) return false; 31 32 return true; 33 } 34 } 35} 36 37
という最後の部分、むちゃくちゃ繰り返しで保守性悪そうじゃないですか。
で、
C#
1List<WindowProperty> properties = new List<WindowProperty>(); 2properties.Add(MainWindowProperty); 3properties.Add(SettingWindowProperty); 4properties.Add(ToolWindowProperty); 5properties.Add(AllMapWindowProperty); 6properties.Add(StatusWindowProperty); 7 8foreach (var property in properties) 9 if (this.property != other.property) 10 return false; 11
としたら楽かもと考えたのです。
ところが、
other.propertyでUserSettingにpropertyがないとエラー。
こういうときって、どうすればよいのでしょう?
List<WindowProperty> properties = new List<WindowProperty>();
をfieldにして、さらにfieldに
public WindowProperty property { get; set; }
を追加するとコード上のエラーはなくなりますが、this.propertyとother.propertyではなくて、propertiesに追加したものをforでくるくる回したいです。
アドバイスお願いします。
回答4件
あなたの回答
tips
プレビュー