Skip to main content
 首页 » 编程设计

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

2024年02月13日13cloudgamer

我正在尝试编写一个函数来创建类型 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; 
}