繁体   English   中英

如何将C#动态变量属性分配给另一个动态对象?

[英]How to assign C# dynamic variable properties to another dynamic object?

我正在尝试编写一个函数,它创建一个Type为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.Name分配给obj

假设您只是尝试复制属性,则根本不需要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;
}

实际上,使用dynamic在这里可能是一件坏事 ; 您传入的对象是匿名类型的实例 - 不需要dynamic 特别是, dynamic成员访问与反射不同,并且您无法保证描述为dynamic的对象将从.GetType().GetProperties()返回任何有趣的内容.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;
}

特别是,这可以像使用反射API一样轻松地使用dynamic API,并且您通常不会看到差异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM