这就是我在许多其他类继承的类中作为方法提出的.这个想法是它允许在相同类型的对象的属性之间进行简单比较.
现在,这确实有效 - 但为了提高我的代码质量,我想我会把它扔出去仔细检查.它怎么能更好/更有效/等等?
/// <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) 我有一个对话框,当它产生时,它会被对象模型中的数据填充.此时,数据被复制并存储在"备份"对象模型中.当用户完成更改并单击"确定"以关闭对话框时,我需要一种快速方法来比较备份对象模型和实时模型 - 如果有任何更改,我可以为用户创建一个新的撤消状态.
如果可能的话,我不想为对象模型中的每个类编写比较函数.
如果我将两个对象模型序列化并且它们相同但存储在不同的内存位置它们是否相等?是否存在比较两个序列化对象模型的简单方法?