mardi 8 août 2017

Assignung any[] to another property of type List

I use reflection (and have to) to assign one value to another. the target object can be of any object, but must itself have specific properties: (Id & Value)

if (sourceValue.Value is FieldLookupValue) {
  var currentPropertyValue = targetProperty.GetValue(entity);
  var subProperties = targetProperty.PropertyType.GetProperties();
  var subId = subProperties.FirstOrDefault(prop => prop.Name.ToLower() == "id" && prop.PropertyType == typeof(int));
  var subValue = subProperties.FirstOrDefault(prop => prop.Name.ToLower() == "value" && prop.PropertyType == typeof(string));

  subId.SetValue(currentPropertyValue, ((FieldLookupValue)sourceValue.Value).LookupId);
  subValue.SetValue(currentPropertyValue, ((FieldLookupValue)sourceValue.Value).LookupValue);
}

This works fine. The target property is of any type that has the properies "Id" and "Value". The source is of a specifiv type (FieldLookupValue) that has the properties LookupId and LookupValue

Now I want to achieve the same with List<object> as targetProperty and FieldLookupValue[] as source.

I already managed to check for the right properties of the elements of the target-List through small modifications:

var innerType = targetProperty.PropertyType.GetGenericArguments()[0];
var subProperties = innerType.GetProperties();
var subId = subProperties.FirstOrDefault(prop => prop.Name.ToLower() == "id" && prop.PropertyType == typeof(int));
var subValue = subProperties.FirstOrDefault(prop => prop.Name.ToLower() == "value" && prop.PropertyType == typeof(string));

Now want I want to achieve is:

[simplified] target.List<SomeProperty> = source.AnotherProperty[] instead of target.SomeProperty=source.AnotherProperty





Aucun commentaire:

Enregistrer un commentaire