mercredi 14 mars 2018

c# generic type class cannot get the property value

Using c# reflection to get & set the value of the generic fields inside a generic object. But I cannot find any way to get the property value of these fields. Code example below:

public class Foo<T>
{
   public bool IsUpdated { get; set; } 
}

public class ItemList: ValueObject<ItemList>
{
   public Foo<string> FirstName;

   public Foo<string> LastName;
}

Problem Getting the 'null' item at the line (*).

itemField.GetType() always return the System.Reflection.RtFieldInfo type but not the Foo type.

I already try using itemField.FieldType.GetProperty("IsUpdated"), it worked when returned the correct property. But threw an error "Object does not match target type." whenever call GetValue() method itemField.FieldType.GetProperty("IsUpdated").GetValue(itemField, null)

Would be appreciate if getting help from anyone!

var itemList = new ItemList();
foreach (var itemList in toValueObject.GetType().GetFields())
{
    var isUpdated = "false";
    var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated"); // (*) return null from here
    if (isUpdatedProp != null)
    {
        isUpdated = isUpdatedProp.GetValue(itemField, null).ToString();
        if (isUpdated == "false") isUpdatedProp.SetValue(itemField, "true");
    }
}





Aucun commentaire:

Enregistrer un commentaire