通用更改跟踪类改进

时间:2015-02-07 20:18:10

标签: c# linq reflection webforms

我正在为变更跟踪开发一个通用的反射类。我所做的一切对于我通过的所有课程都很好。我正准备将其作为整个组的工具的一部分移出。在我向大家演绎之前,我有兴趣进一步改进这一点。它是从具有错误处理的方法调用的,因此该部分不是问题。此外,这在我们的逻辑中完美地用于平衡变化跟踪的对象,但我错过了一些可能成为问题的东西,即使它在通常的情况下也能完美地运行。

public class ChangeTracker
{
    public static string GetChangesString<T,S>(T original, T current, S dto, string[] exluded)
    {
        StringBuilder sb = new StringBuilder();

        PropertyInfo[] names = typeof(S).GetProperties();


        string displayName = string.Empty;
        foreach (PropertyInfo item in names)
        {

            if (exluded.Contains(item.Name)) continue;

            //method that sets display name to either the property name or the display attribute if present
            displayName = GetDisplayName(item);

            object propA = original.GetType().GetProperty(item.Name).GetValue(original, null);
            object propB = current.GetType().GetProperty(item.Name).GetValue(original, null);

            if (propA == null && propB == null) continue;

            if (propA == null && propB != null)
            {
                //appendline for value added
            }
            else if (propB == null && propA != null)
            {
                //appendline for value removed
            }
            else if (propA.ToString() != propB.ToString())
            {
                //appendline for value changed
            }



        }

        return sb.ToString();



    }

    private static string GetDisplayName(PropertyInfo prop)
    {
        string display = string.Empty;
        //Check for displayattribute and set correct name
        return display;
    }
}

具体来说,这是我的问题。

我是否有更好的方法来进行propA和propB设置以提高性能?它适用于一个对象更改,我已经测试了多达103个属性,没有性能问题,但我尽量避免这样的事情。

由于 麦

1 个答案:

答案 0 :(得分:1)

您可以使用Reflection + Expression Trees组合来构建getter Func。我建议在应用程序启动时构建这个表达式并缓存它们(每种类型),这应该可以大大提高性能。但是这会大大增加你的代码基数=)

相关问题