简体   繁体   中英

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 ie 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.

You should make Method1 a generic method, so you don't need to provide type information.

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

C# Generic method docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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