dimanche 18 décembre 2022

c# How to get a value from a method using reflection

Hi how can I execute all methods in a class and get the value from that call I'm stuck at ?????

(I'm using .net 4.8)

I would like to exetute all methods when the program starts, to make sure all config values are in the config file So I dont have ConfigurationManager.AppSettings all over the code but all config values are located in a specific class

public static void CheckConfigValues()
{
    var cv = new ConfigValues();
    var cvt = cv.GetType();
    var cvm = cvt.GetMethods();

    foreach (var item in cvm)
    {
        var itemValue = ?????
        if(string.IsNullOrEmpty(itemValue))
        {
            throw ...
        }
    }
}       
public class ConfigValues
{
    public static int GetMaxCalendarItems()
    {
          return int.Parse(ReadKeyFromAppConfig("GetMaxCalendarItems"));
    }
    
    public static int GetSomething....()
    {
          return int.Parse(ReadKeyFromAppConfig("Something"));
    }
    
    public static string ReadKeyFromAppConfig(string keyName)
    {
        try
        {
            var keyValue = ConfigurationManager.AppSettings[keyName];
            if (!string.IsNullOrEmpty(keyValue))
            {
                return keyValue;
            }
            else
            {
                Logger.Error($"Unable to read variable {keyName});
                throw new MissingFieldException(keyName);
            }   
            




Aucun commentaire:

Enregistrer un commentaire