vendredi 21 janvier 2022

Dynamically use Type for a method in Generic

I have many Schemas as below:

public class Schema1 
{
   public string prop1 {get; set;}
   public int prop2 {get; set;} 
}

public class Schema2 
{
   public DateTime prop3 {get; set;}
   public bool prop4 {get; set;} 
}

Now I want to dynamically get their type and call below method where T is Schema1 or Schema2 and so on. Below method returns objects of T i.e. List, List, List... so on. Below I am passing Type as well in parameter but confused how to use it.

public static List<T> Method1(string param1, out SchemaError[] errors, Type type)
{
List<T> list = new List<T>();   
// other Operations
list = JsonConvert.DeserializeObject<List<T>>(string);
return list;
}

How can I approach this problem? Is there any way through Interface or any design pattern to separate out schemas? I know there is a way through reflection

MethodInfo method = typeof(ClassName).GetMethod(nameof(MethodName));
MethodInfo generic = method.MakeGenericMethod(schemaType);
return generic.Invoke(Activator.CreateInstance(typeof(ClassName)), new object[] { param1 });

but there are some limitations with reflection approach.

Aucun commentaire:

Enregistrer un commentaire