简体   繁体   中英

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);
            }   
            

There are a few suggestions.

You can declare the ReadKeyFromAppConfig method as private.

you are returning int , and int.Parse gives an exception if the value passed is null. so better you int.TryParse and heck for its return value.

I have created a sample class for you, you can use the same concept in your code.

MethodInfo[] methodInfos = Type.GetType("MyNamespace.Test")
                .GetMethods(BindingFlags.Public | BindingFlags.Static);
foreach (MethodInfo methodInfo in methodInfos)
{
    Console.WriteLine(methodInfo.Name);
    var result = methodInfo.Invoke(test, null);
}

internal class Test
{
    public static int Method1()
    {
        return 0;
    }

    public static int Method2()
    {
        return -1;
    }
}

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