gpt4 book ai didi

c# - 获取原始、复杂、数组可枚举类型

转载 作者:行者123 更新时间:2023-11-30 18:44:27 24 4
gpt4 key购买 nike

我的每个数据库实体都有一个单独的类,当我创建我的类的对象以引用类的属性时,它返回一个循环引用,其中也包含通过 FK 相关的其他实体的属性 ...要删除循环引用,我想首先通过“上下文代理对象”副本制作对象的副本,然后获取该对象的原始、复杂、arrayEnumerable 类型,并从对象中剥离这些类型,然后返回对象网络服务....

最佳答案

听起来像是一个递归的浅层克隆。我使用了以下但只深入了一层。

public static class EntityBaseExtensions
{
/// <summary>
/// Description: Creates a non-recursive shallow copy of an entity, only including public instance properties decorated with ColumnAttribute.
/// This will return an object without entity references.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns>A non-recursive shallow copy of a LINQ entity</returns>
public static T ShallowClone<T>(this T source) where T : EntityBaseClass
{
// create an object to copy values into
T destination = Activator.CreateInstance<T>();

// get source and destination property infos for all public instance
PropertyInfo[] sourcePropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
PropertyInfo[] destinationPropInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo sourcePropInfo in sourcePropInfos)
{
if (Attribute.GetCustomAttribute(sourcePropInfo, typeof(ColumnAttribute), false) != null)
{
PropertyInfo destPropInfo = destinationPropInfos.Where(pi => pi.Name == sourcePropInfo.Name).First();

destPropInfo.SetValue(destination, sourcePropInfo.GetValue(source, null), null);
}
}

return destination;
}

}

关于c# - 获取原始、复杂、数组可枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2786386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com