2015-02-07 209 views
0

我正在为更改跟踪开发通用反射类。我所做的所有课程的工作都很好。我准备将它作为整个组的一部分工具移出。在我向所有人角色之前,我有兴趣改进这一点。它从具有错误处理的方法中调用,以便部分不是问题。此外,在我们的逻辑中,这种方式完全符合我们为变更追踪而拼合对象的方式,但是我错过了一些可能成为问题的东西,即使它适用于通常的情况。通用更改跟踪类改进

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个没有性能问题的属性,但是我尽可能避免这样的东西。

感谢 吉米

+0

我投票结束这个问题作为题外话,因为它应该张贴在http://codereview.stackexchange.com – 2015-02-07 20:22:01

+0

授予第4点可能属于codereview,但这个问题的原因实际上是针对SO的第1点和第2点。我不知道如何添加.Where删除if语句,因为它不适用于我尝试过的所有内容。 – Jimmy 2015-02-07 20:40:22

+2

'typeof(S).GetProperties()。Where(p =>!excluded.Contains(p.Name))';) - 你应该真的问每个问题一个问题,但(在适当的网站上)进入你有很多部分答案的情况。当你有4个不同的答案回答4个不同的问题时,你如何接受正确的答案? – 2015-02-07 20:44:28

回答

1

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

+0

我会看看Expression Trees。我认为这不会对我们的一些旧服务器起作用,但我还没有足够的研究来肯定地说。我们将不被允许在应用程序启动时进行确认并缓存它。有时由于感知到的安全风险,表现会走到一边。 – Jimmy 2015-02-07 20:42:38

+0

其实非常感谢您的评论。我不认为我的array.Contains也会在我们的旧服务器上工作。 – Jimmy 2015-02-07 20:43:58

+0

@Jimmy,您使用哪种框架版本进行开发? – 2015-02-07 20:46:08