我想将一个对象克隆到另一个对象,但从原始对象中排除属性。例如,如果对象 A 具有名称、薪水、位置,那么如果我排除了位置属性,则克隆的对象应该仅具有名称和薪水属性。谢谢。
这是我用来执行此操作的扩展方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
您还可以查看 Automapper。
这是我如何使用该扩展的示例。
var skipProperties = new[] { "Id", "DataSession_Id", "CoverNumber", "CusCode", "BoundAttempted", "BoundSuccess", "DataSession", "DataSessions","Carriers" };
DataSession.Quote = new Quote().CloneExcept(lastSession.Quote, skipProperties);
Run Code Online (Sandbox Code Playgroud)
由于这是作为扩展方法实现的,因此它会修改调用对象,并返回它以方便使用。这在[问题]中进行了讨论:克隆不同对象属性的最佳方法
| 归档时间: |
|
| 查看次数: |
3998 次 |
| 最近记录: |