mardi 18 avril 2017

Passing a type instead of a value when using reflection [duplicate]

This question already has an answer here:

I'm trying to use reflection to manually build a ts file, but can't seem to figure out how to do it the correct way. I have a property which will be a list of enum class names (types). For each of these I will call a method with creates a ts file. Method creating files (start):

public static bool CreateJsonFiles<T>(object item, string filePath = null)
{
    try
    {
        var type = item.GetType();
        var values = Enum.GetValues(type).Cast<T>();
        if (filePath == null)
        {
            return false;
        }

Beforehand I used the T generic parameter, by calling the function like

EnumsBuilder.CreateJsonFiles<LocatieType>($"{Server.MapPath("/")}");

The problem is that I wish to call the method for multiple value now (in an iteration). I've tried two things that both do not work: 1.Change generic method to remove parameter, and use typeof(item):

var type = item.GetType();
var values = Enum.GetValues(type).Cast<type >();

This gives an error on the Cast function.

  1. Try to obtain the type of the items in the list in the iteration and try to pass this along:

    public static List<Type> EnumList { get; set; }
    
     public static void BuildEnums(string serverPath)
     {
        foreach (var item in EnumList)
        {
            var type = item.GetType();         
            CreateJsonFiles<type>(type, serverPath);
        } 
     }
    
    

This also gives an error, because this is not allowed either.

Could anyone explain me the correct way to do this?





Aucun commentaire:

Enregistrer un commentaire