简体   繁体   English

使用反射设置对象数组类型的属性值

[英]Set object array-type property value using reflection

I am trying to generate some generic code that can create C# objects from text generated by another system. 我正在尝试生成一些通用代码,这些代码可以从另一个系统生成的文本创建C#对象。 The object is to be used for a method call - the method call is also going to be done by reflection. 该对象将用于方法调用-方法调用也将通过反射来完成。 When I am creating this method parameter object, I could not figure out how to instantiate and assign values to a property that is array type. 创建此方法参数对象时,我无法弄清楚如何实例化并将值分配给数组类型的属性。 I can use the setValue to assign to "name" in the code sample below, but how to assign values to the array? 我可以在下面的代码示例中使用setValue分配给“名称”,但是如何为数组分配值呢?

class Car {
    public string name { get; set; }
    public Door[] doors { get; set; }
}

class Door {
    public int index { get; set; }
    public bool isDusty { get; set; }
}

public object createMethodParameter(Vehicle<T> v)

    object methodParameter;

    Type type = v.GetType();

    PropertyInfo[] properties;
    MethodInfo[] mi = type.GetMethods();

    ParameterInfo[] pi;

    foreach (var method in mi)
    {
        if ("create".Equals(method.Name.ToLowerInvariant())) // look for the create method
        {
            pi = method.GetParameters();
            foreach (var param in pi)
            {
                returnValue = Activator.CreateInstance(param.ParameterType);
                properties = param.ParameterType.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    if (property.PropertyType.IsArray)
                    {
                        // how to create the doors array on the car??
                    }
                    else
                    {
                        property.SetValue(methodParameter, "Porsche", null);
                    }
                }
            }
        }
    }
    return methodParameter;
}
Array.CreateInstance(property.PropertyType.GetElementType(), 4)

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

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