mardi 22 janvier 2019

Using methods with reflection c#

im trying to make an implementacion of a dictionary that goes Dictionary<string, Func<string[], string>> with reflection. As of right now i got it working like this

        lCommands.Add(new string[] { "help", "ayuda" }, HelpFunc);
        lCommands.Add(new string[] { "cambiacargo", "ccl" }, CambiarCargoLegislador);
        lCommands.Add(new string[] { "buscar" }, ObtenerDatosLegislador);
        lCommands.Add(new string[] { "listartiemposbloques" }, ObtenerTiemposBloques);
        lCommands.Add(new string[] { "modificartiemposbloques" }, ModificarTiempoBloque);
        lCommands.Add(new string[] { "logout" }, logout);
        lCommands.Add(new string[] { "tienepalabra", "hablado" }, TiempoPalabraActivo);

where the .Add is an extension method that takes an array of string, and a Func and make it keys for the same Func. My problem actually is that i would like to be able to this with reflection. So after searching for a while I ve been able to come up with this

   foreach (MethodInfo methodInfo in typeof(CommandHelper).GetMethods(BindingFlags.NonPublic | BindingFlags.Static))
    {
        string methodName = methodInfo.Name;

        object[] attribute = methodInfo.GetCustomAttributes(typeof(Command), true);

        if (attribute.Length > 0)
        {
            Command myAliases = (Command)attribute[0];

            lCommands.Add(myAliases.alias, /* here is my problem propertyInfo.Name*/);
        }
    }

but im not sure how to transform the methodInfo into a Func<string[],string>. To sum it up, i want to do the same for the first chunk of code with reflection

Just in case someone need it this is an example of one of the functions

    [Help(Remainder = "Obtiene el tiempo hablado por un legislador")]
    [Command("tienepalabra,hablado,tpa")]
    private static string TiempoPalabraActivo(string[] arg)
    {
        LegisladorService leServ = new LegisladorService();
        try
        {
            return $"el legislador {leServ.TraerPorIdNombreApellido(Form1._server.tienePalabra)} estuvo hablando durante {Form1._server.TiempoPalabra()}";
        }
        catch (Exception)
        {
            return "No hay legislador con palabra activo";
        }
    }

Thanks in advance





Aucun commentaire:

Enregistrer un commentaire