相关疑难解决方法(0)

查找两个C#对象之间的属性差异

我正在处理的项目需要一些简单的审计日志记录,以便用户更改其电子邮件,帐单地址等.我们正在使用的对象来自不同的来源,一个是WCF服务,另一个是Web服务.

我已经使用反射实现了以下方法来查找对两个不同对象的属性的更改.这将生成一个属性列表,这些属性与旧值和新值有差异.

public static IList GenerateAuditLogMessages(T originalObject, T changedObject)
{
    IList list = new List();
    string className = string.Concat("[", originalObject.GetType().Name, "] ");

    foreach (PropertyInfo property in originalObject.GetType().GetProperties())
    {
        Type comparable =
            property.PropertyType.GetInterface("System.IComparable");

        if (comparable != null)
        {
            string originalPropertyValue =
                property.GetValue(originalObject, null) as string;
            string newPropertyValue =
                property.GetValue(changedObject, null) as string;

            if (originalPropertyValue != newPropertyValue)
            {
                list.Add(string.Concat(className, property.Name,
                    " changed from '", originalPropertyValue,
                    "' to '", newPropertyValue, "'"));
            }
        }
    }

    return list;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找System.IComparable,因为"所有数字类型(如Int32和Double)都实现IComparable,String,Char和DateTime也是如此." 这似乎是找到任何不是自定义类的属性的最佳方法.

利用由WCF或Web服务代理代码生成的PropertyChanged事件听起来不错,但没有为我的审计日志(旧值和新值)提供足够的信息.

如果有更好的方法来寻找输入,谢谢!

@Aaronaught,这里是一些基于执行object.Equals生成正匹配的示例代码:

Address …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection auditing

55
推荐指数
3
解决办法
3万
查看次数

标签 统计

.net ×1

auditing ×1

c# ×1

reflection ×1