"深度"转换对象

Can*_*ide 3 c#

我有以下方法可用于将对象转换为给定类型:

public static TTarget Convert<TTarget>(object source) where TTarget : new()
{
    var target = new TTarget();

    Type targetType = typeof (TTarget);
    foreach (PropertyInfo sourceProperty in source.GetType().GetProperties())
    {
        if (!sourceProperty.CanRead || (sourceProperty.GetIndexParameters().Length > 0))
            continue;

        PropertyInfo targetProperty = targetType.GetProperty(sourceProperty.Name);

        if ((targetProperty != null) && (targetProperty.CanWrite))
            targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
    }
    return target;
}
Run Code Online (Sandbox Code Playgroud)

它适用于具有属性值类型等的简单类,但复杂属性需要映射到另一个类,它不是很清楚如何去做.如果我将映射存储到静态属性中:

private static Dictionary<Type, Type> Mappings;

static TypeConverter()
{
    Mappings = new Dictionary<Type, Type>
        {
            {typeof (DbSpace), typeof (DmsSpace)},
            {typeof (DbDirectory), typeof (DmsDirectory)},
            {typeof (DbFile), typeof (DmsFile)}
        };
}
Run Code Online (Sandbox Code Playgroud)

我似乎没有办法找到一种方法来利用这些信息来转换复杂的属性.如何使用上述映射转换复杂属性?

问题的症结在于:new如果我只有一个Type物体,我该如何打电话?

And*_*eas 5

Activator.CreateInstance(type),这里有一个链接到msdn的那些认为我的答案不够"精心"的人(得到3个downvotes,一个现场开始作为简短必要的答案)......

你有没看过AutoMapper