1

我正在尝试编写一个函数来创建类型 t 的对象并分配其属性。

    internal static object CreateInstanceWithParam(Type t, dynamic d)
    {
        //dynamic obj =  t.GetConstructor(new Type[] { d }).Invoke(new object[] { d });

        dynamic obj =  t.GetConstructor(new Type[] { }).Invoke(new object[] { });
        foreach (var prop in d.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
        {
            //prop.Name, 
            //prop.GetValue(d, null);

            // assign the properties and corresponding values to newly created object ???
        }
        return obj;
    }

然后我应该可以将它用于任何类型的类类型,例如

IUser user = (IUser)CreateInstanceWithParam(userType, new { UserID = 0, Name = "user abc", LoginCode = "abc", DefaultPassword = "xxxxxx" });

IUnit newUnit = (IUnit)CreateInstanceWithParam(unitType, new { ID = 3, Code = "In", Name = "Inch", Points = "72" })

如何将属性分配prop.Nameobj

4

2 回答 2

3

假设您只是想复制属性,则根本不需要dynamic

internal static object CreateInstanceWithParam(Type type, object source)
{
    object instance = Activator.CreateInstance(type);
    foreach (var sourceProperty in d.GetType()
                                    .GetProperties(BindingFlags.Instance | 
                                                   BindingFlags.Public))
    {
        var targetProperty = type.GetProperty(sourceProperty.Name);
        // TODO: Check that the property is writable, non-static etc
        if (targetProperty != null)
        {
            object value = sourceProperty.GetValue(source);
            targetProperty.SetValue(instance, value);
        }
    }
    return instance;
}
于 2013-06-20T07:24:57.570 回答
1

实际上,在这里使用dynamic可能是一件坏事;您传入的对象是匿名类型的实例 - 不需要dynamic. 特别是,dynamic成员访问与反射不同,您不能保证描述为的对象会从;dynamic返回任何有趣的东西。.GetType().GetProperties()考虑ExpandoObject

但是,FastMember(在 NuGet 上可用)可能有用:

internal static object CreateInstanceWithParam(Type type, object template)
{
    TypeAccessor target = TypeAccessor.Create(type),
        source = TypeAccessor.Create(template.GetType());
    if (!target.CreateNewSupported)
            throw new InvalidOperationException("Cannot create new instance");
    if (!source.GetMembersSupported)
            throw new InvalidOperationException("Cannot enumerate members");
    object obj = target.CreateNew();
    foreach (var member in source.GetMembers())
    {
        target[obj, member.Name] = source[template, member.Name];
    }
    return obj;
}

特别是,这可以dynamic像使用反射 API 一样轻松地使用 API,而且您通常看不到其中的区别。

于 2013-06-20T07:28:19.323 回答