这就是我在许多其他类继承的类中作为方法提出的.这个想法是它允许在相同类型的对象的属性之间进行简单比较.
现在,这确实有效 - 但为了提高我的代码质量,我想我会把它扔出去仔细检查.它怎么能更好/更有效/等等?
/// <summary>
/// Compare property values (as strings)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool PropertiesEqual(object comparisonObject)
{
Type sourceType = this.GetType();
Type destinationType = comparisonObject.GetType();
if (sourceType == destinationType)
{
PropertyInfo[] sourceProperties = sourceType.GetProperties();
foreach (PropertyInfo pi in sourceProperties)
{
if ((sourceType.GetProperty(pi.Name).GetValue(this, null) == null && destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null) == null))
{
// if both are null, don't try to compare (throws exception)
}
else if (!(sourceType.GetProperty(pi.Name).GetValue(this, null).ToString() == destinationType.GetProperty(pi.Name).GetValue(comparisonObject, null).ToString()))
{
// only …
Run Code Online (Sandbox Code Playgroud) 比较两个对象并找出差异的最佳方法是什么?
Customer a = new Customer();
Customer b = new Customer();
Run Code Online (Sandbox Code Playgroud) 假设我有这样的结构
public class Form
{
#region Public Properties
public List<Field> Fields { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public int Revision { get; set; }
#endregion
}
Run Code Online (Sandbox Code Playgroud)
所以Form
该类包含字段列表,假设字段本身用这种结构表示
public class Field
{
#region Public Properties
public string DisplayName { get; set; }
public List<Field> Fields { get; set; }
public string Id { get; set; }
public FieldKind Type { …
Run Code Online (Sandbox Code Playgroud)