我想将一个对象克隆到另一个对象,但从原始对象中排除一个属性。例如,如果对象 A 具有名称、薪水、位置,那么如果我排除了位置属性,则克隆的对象应该只有名称和薪水属性。谢谢。
问问题
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,那么您可以尝试“瞬态”关键字。至少这适用于序列化。
于 2012-02-17T01:30:16.883 回答