2012-02-17 85 views

回答

0

下面是我用来做一个扩展方法:

public static T CloneExcept<T, S>(this T target, S source, string[] propertyNames) 
{ 
    if (source == null) 
    { 
     return target; 
    } 
    Type sourceType = typeof(S); 
    Type targetType = typeof(T); 
    BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance; 

    PropertyInfo[] properties = sourceType.GetProperties(); 
    foreach (PropertyInfo sPI in properties) 
    { 
     if (!propertyNames.Contains(sPI.Name)) 
     { 
      PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags); 
      if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType)) 
      { 
       tPI.SetValue(target, sPI.GetValue(source, null), null); 
      } 
     } 
    } 
    return target; 
} 

您可能还检查出Automapper。

这里是我如何使用扩展的一个例子。

var skipProperties = new[] { "Id", "DataSession_Id", "CoverNumber", "CusCode", "BoundAttempted", "BoundSuccess", "DataSession", "DataSessions","Carriers" }; 
DataSession.Quote = new Quote().CloneExcept(lastSession.Quote, skipProperties); 

由于这是作为扩展方法实现的,因此它会修改调用对象并为了方便而返回它。这是在[question]中讨论的:Best way to clone properties of disparate objects

0

如果您在谈论java,那么您可以尝试使用“transient”关键字。至少这适用于序列化。

+1

不,我正在使用C#。 – user282807 2012-02-17 01:30:55

+0

@ user282807下一次为该问题设置适当的语言标记(如果语言特定的话) - 可以节省解析不相关的答案和其他写入的问题;-)幸运的是,好的社区成员这次已经为您添加了该标记 – mbx 2018-01-23 12:35:43