lundi 27 novembre 2017

c# reflection - convert string to type of FieldInfo.GetType()

I have an app that loads settings from the command line, they come as strings, but i might have a lot of settings at some time.

I have this so far.

class Settings
{
    public static int TestSetting;

    public static void Load(string[] settings)
    {
        FieldInfo[] fields = typeof(Settings).GetFields();

        foreach(string setting in settings)
        {
            string[] settingSplit = setting.Split('=');

            string settingName = settingSplit[0];
            string settingValue = settingSplit[1];

            foreach(FieldInfo field in fields)
            {
                if(field.Name == settingName)
                {
                    field.SetValue(null, Convert.ChangeType(settingValue, field.GetType()));
                }
            }
        }

        Console.WriteLine(TestSetting);
    }
}

Should be used like this:

Settings.Load(new string[] { "TestSetting=13" });

So as you can see i first get all the FieldInfo's from my Settings class, then i iterate through the settings, each setting is composed of "SettingName=SettingValue" and for each i verify if its name is the same as the field's, if it is then i try to convert the string to the field type, it fails with:

System.InvalidCastException occurred
Invalid cast from 'System.String' to 'System.Reflection.RtFieldInfo'.





Aucun commentaire:

Enregistrer un commentaire