获取原始的,复杂的,Array Enumerable类型

时间:2010-05-07 05:26:45

标签: c# reflection

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

1 个答案:

答案 0 :(得分:0)

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

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

}