private static Action <object, object> GetOrAddCopier(Type key)
        {
            // Validate parameters.
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            // Lock on the copiers.
            lock (CopyFieldCopiers)
            {
                // Try and get the value.
                if (CopyFieldCopiers.TryGetValue(key, out var copier))
                {
                    return(copier);
                }

                // Set the copier.
                copier = CreateCopier(key);

                // Add it.
                CopyFieldCopiers.Add(key, copier);

                // Return the copier.
                return(copier);
            }
        }
Esempio n. 2
0
        public static T CopyFields <T>(T instance)
            where T : class, new()
        {
            // Validate parameters.
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            // The type.
            Type type = typeof(T);

            // Add or create the copier.
            Action <object, object> copier = CopyFieldCopiers.GetOrAdd(type, CreateCopier);

            // Get the uninitialized object.
            // TODO: Get FormatterServices which has GetSafeUninitializedObject, remove new() constraint.
            var t = new T();

            // Copy.
            copier(instance, t);

            // Return t.
            return(t);
        }