vendredi 18 février 2022

How to get the value of a property and assign it to another property using reflection C#

I have some classes

public class Response<T>
    {
       public string request_id { get; set; }
       public T data { get; set; }
    }



   Public class Model1
{
   public string Field1 { get; set; }
   public string Field2 { get; set; }
}

Public class Model2
    {
       public string Field3 { get; set; }
       public string Field4 { get; set; }
    }

Public class CommonModel
        {
           public Model1 Model1 { get; set; }
           public Model2 Model2 { get; set; }
        }

As a T i use Model 1 or Model2.

For Example i have Instance of Model1

var modelInstance = Activator.CreateInstance(modelType);

But when i try

var result  = responseObject.GetType().GetProperty("data").GetValue(modelInstance);

I get "Object does not match target type." Exception

How can i get data property from responseObject and set in to CommonModel.{PropertyName} using reflection





Aucun commentaire:

Enregistrer un commentaire