Home > Enterprise >  How to pass and iterate over List<T> in a generic function
How to pass and iterate over List<T> in a generic function

Time:11-29

First of all the purpose of this code is to reset static variables of a class when required i know its not an elegant solution but that's only what can be done for now at least . Here's the code

public static void ResetStaticObjects<T>()
{
    var type = typeof(T);
    if (type != null)
    {
        var items = type.GetProperties(BindingFlags.Public | BindingFlags.Static);
        foreach (var item in items)
        {
            item.SetValue(type, null, null);
        }
    }
}

and this is how i am calling it right now

HelperClass.ResetStaticObjects<DemoClass>();

what i want is to pass a list instead of passing one class then call the same function on all of these classes

CodePudding user response:

Below is the answer to the question i posted

public static void ResetStaticObjects<Type>(IEnumerable<Type>types)where Type:System.Type
{
     foreach(var item in types)
     {         
              var props = item.GetProperties(BindingFlags.Public | BindingFlags.Static);
              foreach (var prop in props)
              {
                  prop.SetValue(item, null, null);
              }        
     }
}

and here's how we can call it

HelperClass.ResetStaticObjects(new[] { typeof(Class1), typeof(Class2)});
  • Related