Как скопировать значение от класса X до класса Y с тем же именем свойства в c#?

Сначала проверьте, распознает ли командная строка команду mysql. Если не идти в команду & amp; введите:

set path=c:\wamp\bin\mysql\mysql5.1.36\bin

Затем используйте эту команду для экспорта вашей базы данных:

mysqldump -u YourUser -p YourDatabaseName > wantedsqlfile.sql

После этого вам будет предложено ввести пароль базы данных.

экспортирует базу данных по пути, в котором вы сейчас находитесь, при выполнении этой команды

Примечание: Ниже приведены некоторые подробные инструкции относительно импорта и экспорта g6]

16
задан Samnang 10 February 2009 в 08:40
поделиться

5 ответов

Списки делают это хитрым... мой более ранний ответ (ниже) только относится к сопоставимым свойствам (не списки). Я подозреваю, что Вам, возможно, просто придется записать и поддержать код:

    Student foo = new Student {
        Id = 1,
        Name = "a",
        Courses = {
            new Course { Key = 2},
            new Course { Key = 3},
        }
    };
    StudentDTO dto = new StudentDTO {
        Id = foo.Id,
        Name = foo.Name,
    };
    foreach (var course in foo.Courses) {
        dto.Courses.Add(new CourseDTO {
            Key = course.Key
        });
    }
<час>

редактирование; только относится мелкий копии - не списки

, Отражение является опцией, но медленный. В 3,5 можно встроить это в скомпилированный бит кода с Expression. У Jon Skeet есть предварительно прокрученный образец этого в , MiscUtil - просто использует как:

Student source = ...
StudentDTO item = PropertyCopy<StudentDTO>.CopyFrom(student);

, поскольку это использует скомпилированный Expression, это значительно превзойдет отражение по характеристикам.

, Если Вы не имеете 3.5, затем используйте отражение или ComponentModel. При использовании ComponentModel можно, по крайней мере, использовать HyperDescriptor для получения его почти столь же быстрые как Expression

Student source = ...
StudentDTO item = new StudentDTO();
PropertyDescriptorCollection
     sourceProps = TypeDescriptor.GetProperties(student),
     destProps = TypeDescriptor.GetProperties(item),
foreach(PropertyDescriptor prop in sourceProps) {
    PropertyDescriptor destProp = destProps[prop.Name];
    if(destProp != null) destProp.SetValue(item, prop.GetValue(student));
}
17
ответ дан 30 November 2019 в 16:50
поделиться

Хорошо я просто искал MiscUtil, который Marc отправил об и его просто потрясающий. Я надеюсь, что метка не возражает против меня добавляющий код здесь.

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<int> Courses { get; set; }
            public static implicit operator Student(StudentDTO studentDTO)
            {
                return PropertyCopy<Student>.CopyFrom(studentDTO);
            }
        }

        public class StudentDTO
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public IList<int> Courses { get; set; }
            public static implicit operator StudentDTO(Student student)
            {
                return PropertyCopy<StudentDTO>.CopyFrom(student);
            }
        }


        static void Main(string[] args)
        {
            Student _student = new Student();
            _student.Id = 1;
            _student.Name = "Timmmmmmmmaaaahhhh";
            _student.Courses = new List<int>();
            _student.Courses.Add(101);
            _student.Courses.Add(121);

            StudentDTO itemT = _student;

            Console.WriteLine(itemT.Id);
            Console.WriteLine(itemT.Name);
            Console.WriteLine(itemT.Courses.Count);
        }


    }


    // COOLEST PIECE OF CODE FROM - http://www.yoda.arachsys.com/csharp/miscutil/

    /// <summary>
    /// Generic class which copies to its target type from a source
    /// type specified in the Copy method. The types are specified
    /// separately to take advantage of type inference on generic
    /// method arguments.
    /// </summary>
    public class PropertyCopy<TTarget> where TTarget : class, new()
    {
        /// <summary>
        /// Copies all readable properties from the source to a new instance
        /// of TTarget.
        /// </summary>
        public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
        {
            return PropertyCopier<TSource>.Copy(source);
        }

        /// <summary>
        /// Static class to efficiently store the compiled delegate which can
        /// do the copying. We need a bit of work to ensure that exceptions are
        /// appropriately propagated, as the exception is generated at type initialization
        /// time, but we wish it to be thrown as an ArgumentException.
        /// </summary>
        private static class PropertyCopier<TSource> where TSource : class
        {
            private static readonly Func<TSource, TTarget> copier;
            private static readonly Exception initializationException;

            internal static TTarget Copy(TSource source)
            {
                if (initializationException != null)
                {
                    throw initializationException;
                }
                if (source == null)
                {
                    throw new ArgumentNullException("source");
                }
                return copier(source);
            }

            static PropertyCopier()
            {
                try
                {
                    copier = BuildCopier();
                    initializationException = null;
                }
                catch (Exception e)
                {
                    copier = null;
                    initializationException = e;
                }
            }

            private static Func<TSource, TTarget> BuildCopier()
            {
                ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
                var bindings = new List<MemberBinding>();
                foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
                {
                    if (!sourceProperty.CanRead)
                    {
                        continue;
                    }
                    PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
                    if (targetProperty == null)
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
                    }
                    if (!targetProperty.CanWrite)
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
                    }
                    if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
                    {
                        throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
                    }
                    bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
                }
                Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
                return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
            }
        }
    }

}
10
ответ дан 30 November 2019 в 16:50
поделиться

Запишите неявный оператор в любом класс

    public static implicit operator StudentDTO(Student student)
    {

        //use skeet's library

        return PropertyCopy<StudentDTO>.CopyFrom(student);

    }

теперь, можно сделать это

StudentDTO studentDTO = student;
4
ответ дан 30 November 2019 в 16:50
поделиться

FYI

Когда у меня возник тот же вопрос, я нашел AutoMapper ( http: // automapper. codeplex.com/) Затем, после прочтения ответа AboutDev, я сделал простой тест, результаты довольно впечатляющие

здесь результаты теста:

Test Auto Mapper: 22322 ms

Test Implicit Operator: 310 ms

Копия тестового свойства: 250 мс

Test Emit Mapper: 281 мс

И я хотел бы подчеркнуть, что это образец только с классами (StudentDTO, Student), которые имеют только несколько свойств, но что бы произошло бы, если бы классы имели 50-100 свойств, я думаю, это сильно повлияет на производительность.

Более подробная информация о тестах здесь: Подходы к копированию объектов в .net: Auto Mapper, Emit Mapper, Implicit Operation, Property Copy

5
ответ дан 30 November 2019 в 16:50
поделиться

Есть библиотека для этого - http://emitmapper.codeplex.com/

Она намного быстрее, чем AutoMapper, использует System.Reflection.Emit, поэтому код выполняется почти так же быстро, как если бы он был написан вручную.

0
ответ дан 30 November 2019 в 16:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: