2012-02-17 50 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

相關問題