オブジェクトを別のオブジェクトに複製したいが、元のオブジェクトからプロパティを除外したい。たとえば、オブジェクト A に Name、Salary、Location がある場合、Location プロパティを除外すると、複製されたオブジェクトには Name プロパティと Salary プロパティのみが含まれます。ありがとう。
2575 次
2 に答える
3
これを行うために使用する拡張メソッドを次に示します。
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.CanWrite && 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);
これは拡張メソッドとして実装されているため、呼び出し元のオブジェクトを変更し、便宜上それを返します。これは [質問] で説明されました:異なるオブジェクトのプロパティを複製する最良の方法
于 2013-01-08T17:10:34.293 に答える
0
Javaについて話している場合は、「transient」キーワードを試してみてください。少なくともこれはシリアル化で機能します。
于 2012-02-17T01:30:16.883 に答える