2012-02-17 6 views
0

オブジェクトを別のオブジェクトに複製したいが、元のオブジェクトからプロパティを除外したい。例えば、オブジェクトAがName、Salary、Locationを持つ場合、Locationプロパティを除外した場合、クローンオブジェクトはNameプロパティとsalaryプロパティのみを持つ必要があります。ありがとう。オブジェクトを別のオブジェクトに複製しますが、いくつかのプロパティは除外しますか?

答えて

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); 

これは拡張メソッドとして実装されているため、呼び出し元オブジェクトを変更して便宜的に返します。これは[質問]で議論されました:Best way to clone properties of disparate objects

0

あなたがjavaについて話している場合は、「一時的な」キーワードを試してみてください。 atleastこれはシリアル化のために働きます。

+1

いいえ、私はC#を使用しています。 – user282807

+0

@ user282807次回は、言語固有の質問の場合は適切な言語タグを設定します。無関係な答えを解析したり、他の人が記述しないように保存します;-)ありがたいことに素晴らしいコミュニティメンバーが、 – mbx