简体   繁体   中英

How to Pass class name Dynamically to List at Run Time C#

I need to pass the class name as Dynamically to List in Function but I am getting the error as below..

 public void  updateList <T>( T clazz, string classData)
 {                      

     if (string.IsNullOrEmpty(json_response) == false)
     {
         List<clazz> list_of_measurements_Original = JsonConvert.DeserializeObject<List<clazz>>(json_response);
     } // Getting error for ClassType in List
 }

error CS0246: The type or namespace name 'clazz' could not be found (are you missing a using directive or an assembly reference?)

I have a number of classes and I want to update dynamically by the same Generic function by passing the Class name or by enum. I have also used the Dynamic Keyword as a function parameter but no result. Please help me out.

'clazz' is a parameter while the compiler searches for a type. You don't need to pass the type as a parameter, this is what the generics are for. Try this:

    public void  updateList <T>(string classData)
    {

         List<T> objlist = new List<T>(); 
    }

Change

List<clazz> objlist = new List<clazz>();

To

List<T> objlist = new List<T>();

Here T is a type parameter which is a placeholder for a specific type. The compiler changes the T to whatever type you pass. You can't pass a variable (clazz) as a type argument of a generic class.

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